简体   繁体   English

C#字典(顺序键)与Java SortedMap字典顺序

[英]C# Dictionary (Order Keys) versus Java SortedMap lexicographic order

I am using a SortedMap in Java and attempting to order a C# Dictionary by Keys. 我在Java中使用SortedMap,并尝试按键订购C#词典。 Comparing the outputs I would expect to see the same orders, however the orderings are different and I'm not sure why. 比较输出,我希望看到相同的顺序,但是顺序是不同的,我不确定为什么。

SortedMap<String, String> orderedByKey = new TreeMap<>();
orderedByKey.put("0:10", "");
orderedByKey.put("10:12+", "");
orderedByKey.put("2:10", "");
orderedByKey.put("1:10", "");
orderedByKey.put("10:1", "");
Dictionary<string, string> tmp = new Dictionary<string, string>();
tmp.Add("0:10", "");
tmp.Add("10:12+", "");
tmp.Add("2:10", "");
tmp.Add("1:10", "");
tmp.Add("10:1", "");
var orderedByKey = tmp.OrderBy(y => y.Key).ToDictionary(y => y.Key, y => y.Value);

Java orders them as follows... Java对它们的订购如下:

0:10 10:1 10:12+ 1:10 2:10 0:10 10:1 10:12+ 1:10 2:10

C# C#

0:10 1:10 10:1 10:12+ 2:10 0:10 1:10 10:1 10:12+ 2:10

The line I was thinking down here was that my C# ordering had ordered the Dictionary but using a different precedent to Java ie C# considers ':' before '0' and in Java '0' is before ':'. 我在这里想的那一行是我的C#排序已对Dictionary进行了排序,但使用了与Java不同的先例,即C#认为':'在'0'之前,而在Java中'0'在':'之前。

The issue here is that in C#, String.CompareTo takes culture into account by default, which provides a slightly different result than Java's String.compareTo method, which uses pure lexicographical comparison. 这里的问题是,在C#中,默认情况下考虑String.CompareTo的区域性,这与Java的String.compareTo方法(使用纯字典比较)提供的结果略有不同。

If you want the C# string comparison to behave like Java, then we can simply specify StringComparer.Ordinal as the comparison type, which compares just the ordinal position of each character: 如果希望C#字符串比较的行为类似于Java,则可以简单地指定StringComparer.Ordinal作为比较类型,该比较类型仅比较每个字符的顺序位置:

private static void Main()
{
    Dictionary<string, string> tmp = new Dictionary<string, string>
    {
        {"0:10", ""},
        {"10:12+", ""},
        {"2:10", ""},
        {"1:10", ""},
        {"10:1", ""}
    };

    var javaSorted = tmp.OrderBy(item => item.Key, StringComparer.Ordinal)
        .ToDictionary(i => i.Key, i => i.Value);

    Console.WriteLine(string.Join(", ", javaSorted.Select(item => item.Key)));

    GetKeyFromUser("\nDone! Press any key to exit...");
}

Output 输出量

在此处输入图片说明

可能您正在寻找SortedDictionary<TKey,TValue> ,它表示按键排序的键/值对的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM