侧边栏壁纸
博主头像
陌上花 博主等级

回首万事皆休

  • 累计撰写 70 篇文章
  • 累计创建 11 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

CSharp之字典

种向日葵的人
2024-08-30 / 0 评论 / 0 点赞 / 17 阅读 / 0 字

简介

  • 之前在学习和书写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();
  • 显示的结果如下:
    dic_1.png
  • 可以发现最后插入的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();

  • 输出截图:
    dic_2.png

总结

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