排序列表阶等同于C#,而不改变C#秩序 [英] Sorting scala list equivalent to C# without changing C# order

查看:153
本文介绍了排序列表阶等同于C#,而不改变C#秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序在斯卡拉字符串的集合,其结果应该是等同于C#列表结果列表。但对于以下数据,C#返回结果以不同的顺序和Scala返回结果的顺序不同。 ?谁能告诉我谁做的结果对双方语言的任何类型的字符串相同



C#代码:



 列表<串GT;名单=新名单,LT;弦乐>(); 
list.Add(bmw_sip);
list.Add(bmw_mnt);
list.Add(BMW1);
list.Add(宝马);
list.Sort();
的foreach(列表中的字符串数据)
{
Console.Write(数据+);
}



输出:



 宝马bmw_mnt bmw_sip BMW1 

Scala代码:

  VAR列表=列表(bmw_sip,bmw_mnt,BMW1 ,宝马)
list.sorted

输出:

 列表[字符串] =名单(宝马,BMW1,bmw_mnt,bmw_sip)


解决方案

Scala的实施整理列表[字符串] 最终使用由 java.lang.String中的compareTo 方法C>,其执行一个词典比较(如由 DOC )。



Unicode值 1'_' 49和95,分别在一个事实:

 _的compareTo1
// INT = 46

在另一方面,排序()在C#使用的Comparer<串GT; .DEFAULT 它执行语言环境敏感的比较。您可以使用 分页器

  VAL ORD = Ordering.comparatorToOrdering(java.text中.Collat​​or.getInstance)
名单(bmw_sip,bmw_mnt,BMW1,宝马)排序(ORD)
//列表[字符串] =名单(宝马,bmw_mnt,bmw_sip ,BMW1)

和只涉及到前面的例子

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

请注意,此方式排序取决于当前区域(因为它在原始C#代码那样)



只是为了保持完整性,如果你不是要执行在C#中的词典式的比较,你必须使用一个 StringComparer.Ordinal

  list.Sort(StringComparer.Ordinal); 


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)

解决方案

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

这篇关于排序列表阶等同于C#,而不改变C#秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆