简体   繁体   English

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

[英]How to sort an OrderedDictionary using Linq in C# (using .NET 3.5)?

I need to sort an OrderedDictionary (System.Collections.Specialized) I have this code: 我需要对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);

I wish to sort it using values. 我希望使用值对其进行排序。 Can I do it using Linq? 我可以使用Linq吗?

Following will give you a sorted dictionary based on your OrderedDictionary. 以下将根据您的OrderedDictionary为您提供一个排序字典。

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

There is one thing though, ToDictionary returned a regular dictionary but the order is maintained in the dictionary for the lookup, as soon as any new item is inserted in the dictionary, they the order cannot be guaranteed. 但有一件事, ToDictionary返回了一个常规字典,但是在字典中维护了查找顺序,只要在字典中插入任何新项目,就无法保证顺序。 To avoid this, use SortedDictionary<TKey,TValue> which has a constructor that takes a regular dictionary as parameter 要避免这种情况,请使用SortedDictionary<TKey,TValue> ,它具有将常规字典作为参数的构造函数

var sortedDictionary = new SortedDictionary<string, string>(normalOrderedDictionary);

(Make sure to replace string with the correct types for Key and value in the above line) . (确保使用上面一行中Key和value的正确类型替换string

Output: 输出:

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

You can enumerate over the values/entries by the value easily. 您可以轻松地按值枚举值/条目。 You'll just have to cast to the appropriate type in order to activate the linq features. 您只需要转换为适当的类型以激活linq功能。

var sortedOrder = od.Values
    .Cast<int>()        // this is an enumeration of ints
    .OrderBy(i => i);;  // enumerate through ordered by the value

foreach (var item in sortedOrder)
{
    // do stuff
}

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

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