Dictionary是无序的,如果想排序,需要使用SortDictionary.

Dictionary本身可以使用linq或者自定义排序,SortDictionary只要插入元素就自动按Key进行了排序

1、下面是一个简单用法示例

static void Main(string[] args)
{
    SortedDictionary<int, string> sd = new SortedDictionary<int, string>();
    sd.Add(3, "张三");
    sd.Add(1, "李四");
    sd.Add(2, "王五");

    foreach (var item in sd)
    {
        Console.WriteLine(item.Value);
    }
}

Dictionary与SortedDictionary

 

 2、SortedDictionary依然支持lLinq Order语句

static void Main(string[] args)
{
    SortedDictionary<int, string> sd = new SortedDictionary<int, string>();
    sd.Add(3, "张三");
    sd.Add(1, "李四");
    sd.Add(2, "王五");

    foreach (var item in sd)
    {
        Console.WriteLine(item.Value);
    }

    var v=sd.OrderByDescending(c => c.Value);
    foreach (var item in v)
    {
        Console.WriteLine(item.Value);
    }
}

返回的是IOrderedEnumerable<TElement>类型,

Dictionary与SortedDictionary

 

相关文章:

  • 2021-08-30
  • 2021-10-08
  • 2022-12-23
  • 2022-12-23
  • 2021-09-30
  • 2022-12-23
  • 2022-01-17
  • 2021-11-06
猜你喜欢
  • 2021-10-22
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-11-27
相关资源
相似解决方案