Dusk
Dusk

Reputation: 2201

Sorting scala list equivalent to C# without changing C# order

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)

Upvotes: 4

Views: 251

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108121

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);

Upvotes: 7

Mehmet Salih Yildirim
Mehmet Salih Yildirim

Reputation: 101

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

Upvotes: -1

Related Questions