c#如何对字典进行按值排序?

SortedDictionary是按键而非值进行排序。

我想对字典进行按值排序。
例如字典的键值对是 单词和出现的次数。

该如何根据出现的次数对字典进行排序?

解决方案:

在C# 3.0中,我们可以这样做:

foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))
{ 
    //do something with item.Key and item.Value
}

或者通过遍历整个Dictionary并查看每个值。

Dictionary<string, string> s = new Dictionary<string, string>();
s.Add("1", "a Item");
s.Add("2", "c Item");
s.Add("3", "b Item");

List<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);
myList.Sort(
    delegate(KeyValuePair<string, string> firstPair,
    KeyValuePair<string, string> nextPair)
    {
        return firstPair.Value.CompareTo(nextPair.Value);
    }
);

如果是.NET 2.0,还可以使用

var myList = aDictionary.ToList();

myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));

使用LINQ:

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
日期:2020-03-23 15:33:03 来源:oir作者:oir