简介
- 之前在学习和书写
C#
代码的时候,对于字典一直以为它的顺序是按照插入的顺序来判定的,但是昨天在更改公司代码的时候发现并不是的,然后仔细找了之后才知道,字典的排序顺序是按照哈希值排列的。这么说可能会很迷茫,简单举例。
操作
var dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("banana", 2);
dictionary.Add("cherry", 3);
dictionary.Add("date", 4);
dictionary.Add("elderberry", 5);
Console.WriteLine("Dictionary contents:");
foreach (var item in dictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Console.WriteLine();
dictionary.Remove("banana");
dictionary.Add("banana", 6);
Console.WriteLine("Dictionary contents:");
foreach (var item in dictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Console.ReadKey();
- 显示的结果如下:

- 可以发现最后插入的
banana
并不是显示在最后一个,内部按照哈希值排序。所以这给我惊醒的是以后在对字典进行删除再插入的时候顺序问题。
- 针对上述这种情况,如果需要按照最后
value
的大小排序应该如何做呢,以下代码示例:
var dictionary = new Dictionary<string, int>();
dictionary.Add("apple", 1);
dictionary.Add("banana", 2);
dictionary.Add("cherry", 3);
dictionary.Add("date", 4);
dictionary.Add("elderberry", 5);
Console.WriteLine("Dictionary contents:");
foreach (var item in dictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Console.WriteLine();
dictionary.Remove("banana");
dictionary.Add("banana", 6);
Console.WriteLine("Dictionary contents:");
foreach (var item in dictionary)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Console.WriteLine();
var orderDic = new Dictionary<string, int>();
orderDic = dictionary.OrderBy(p => p.Value).ToDictionary(p => p.Key, p => p.Value);
Console.WriteLine("Sorted Dictionary contents:");
foreach (var item in orderDic)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Console.ReadKey();
- 输出截图:

总结
- 对于字典操作,如果只是添加然后取值其实问题并不大,但是如果删除再添加同样的键值就需要注意这个问题了,当前你也可以试试
OrderedDictionary
等。我也是改公司代码发现之前写的代码问题很大才注意到,需要之后开发能注意,同时希望以后不要闹笑话0-0.