4

I'm trying to sort the list with collection of string in scala, whose result should be identical to the C# list result. But for the following data, C# returning the result in different order and scala returning the result in different order. Could anyone please tell me who to make the result for both the language identical for any type of string?

C# Code:

List<String> list = new List<String>();
    list.Add("bmw_sip");
    list.Add("bmw_mnt");
    list.Add("bmw1");
    list.Add("bmw");
    list.Sort();
    foreach (String data in list)
    {
        Console.Write(data+" ");
    }

Output:

bmw bmw_mnt bmw_sip bmw1

Scala Code:

var list = List("bmw_sip", "bmw_mnt", "bmw1", "bmw")
list.sorted

Output:

List[String] = List(bmw, bmw1, bmw_mnt, bmw_sip)
Dusk
  • 2,191
  • 6
  • 38
  • 57
  • The difference here is that `1` is considered before `_` in C#, but not in scala. Should look into how to change the alphabetic order of the sorting method in scala. I'd help if I knew what scala even was - this is just a hint for other viewers. – SimpleVar Aug 18 '14 at 11:15
  • Try `list = list.OrderBy(x => x, StringComparer.Ordinal).ToList();` – L.B Aug 18 '14 at 11:24
  • I'm actually looking for change in scala code to make it identical to C# list result. – Dusk Aug 18 '14 at 11:47

2 Answers2

7

Scala's implementation of sorted on a List[String] ultimately uses the compareTo method defined by java.lang.String, which performs a lexicographic comparison (as explained in details by the doc).

The Unicode values of '1' and '_' are 49 and 95, respectively, in fact:

"_" compareTo "1"
// Int = 46

On the other hand, Sort() in C# uses Comparer<String>.Default which performs a locale-sensitive comparison. You can achieve the same result in scala using a Collator:

val ord = Ordering.comparatorToOrdering(java.text.Collator.getInstance)
List("bmw_sip", "bmw_mnt", "bmw1", "bmw").sorted(ord)
// List[String] = List(bmw, bmw_mnt, bmw_sip, bmw1)

and just to relate to the previous example

ord.compare("_", "1")
// Int = -1

Note that this way the sorting depends on the current locale (as it did in the original C# code)

Just for completeness, if you instead want to perform a lexicographic comparison in C#, you have to use a StringComparer.Ordinal:

list.Sort(StringComparer.Ordinal);
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • Now there's an answer! I'd even put the "on the other hand" section as the "here is your great solution" section at the beginning of the answer. – SimpleVar Aug 18 '14 at 12:00
-1

You can use list.Sort() method in order to do that. Sort() method invokes default comparer, if you want to change how it sorts please refer to http://msdn.microsoft.com/en-us/library/234b841s(v=vs.110).aspx