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


i'm trying sort list collection of string in scala, result should identical c# list result. following data, c# returning result in different order , scala returning result in different order. please tell me make result both language identical 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) 

scala's implementation of sorted on list[string] uses compareto method defined java.lang.string, performs lexicographic comparison (as explained in details doc).

the unicode values of '1' , '_' 49 , 95, respectively, in fact:

"_" compareto "1" // int = 46 

on other hand, sort() in c# uses comparer<string>.default performs locale-sensitive comparison. can achieve same result in scala using 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 relate previous example

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

note way sorting depends on current locale (as did in original c# code)

just completeness, if instead want perform lexicographic comparison in c#, have use stringcomparer.ordinal:

list.sort(stringcomparer.ordinal); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -