如何将OrderedDictionary在C#中使用LINQ(使用.net 3.5)进行排序?如何将、OrderedDictionary、LINQ、net

由网友(此用户已离线)分享简介:我需要一个OrderedDictionary排序(System.Collections.Specialized)我有这个code:I need to sort an OrderedDictionary (System.Collections.Specialized)I have this code:var od...

我需要一个OrderedDictionary排序(System.Collections.Specialized) 我有这个code:

I need to sort an OrderedDictionary (System.Collections.Specialized) I have this code:

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

我想用值来排序。我能做到这一点使用LINQ?

I wish to sort it using values. Can I do it using Linq?

推荐答案

下面就给您根据您OrderedDictionary排序的字典。

Following will give you a sorted dictionary based on your OrderedDictionary.

var sortedDictionary= od.Cast<DictionaryEntry>()
                       .OrderBy(r=> r.Value)
                       .ToDictionary(c=> c.Key, d=> d.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
阅读全文

相关推荐

最新文章