如何在C#中使用Linq对OrderedDictionary进行排序(使用.NET 3.5)?

Lal*_*edi 9 .net c# linq

我需要对OrderedDictionary进行排序(System.Collections.Specialized)我有这样的代码:

var od = new System.Collections.Specialized.OrderedDictionary();
od.Add("a1", 3);
od.Add("a2", 5);
od.Add("a3", 2);
od.Add("a4", 4);
Run Code Online (Sandbox Code Playgroud)

我希望使用值对其进行排序.我可以使用Linq吗?

Hab*_*bib 7

以下将根据您的OrderedDictionary为您提供一个排序字典.

var normalOrderedDictionary= od.Cast<DictionaryEntry>()
                       .OrderBy(r=> r.Value)
                       .ToDictionary(c=> c.Key, d=> d.Value);
Run Code Online (Sandbox Code Playgroud)

但有一件事,ToDictionary返回一个普通字典,但订单在字典中维护查找,只要在字典中插入任何新项目,就无法保证订单.为避免这种情况,请使用SortedDictionary<TKey,TValue>具有将常规字典作为参数的构造函数

var sortedDictionary = new SortedDictionary<string, string>(normalOrderedDictionary);
Run Code Online (Sandbox Code Playgroud)

(确保string在上面的行中替换Key和value的正确类型).

输出:

foreach (var entry in sortedDictionary)
    Console.WriteLine("Key: {0} Value: {1}", entry.Key, entry.Value);

Key: a3 Value: 2
Key: a1 Value: 3
Key: a4 Value: 4
Key: a2 Value: 5
Run Code Online (Sandbox Code Playgroud)

  • 好的,谢谢.必须说stackoverflow只是摇滚.. !! (2认同)