我想根据字典的值对字典进行排序并获得结果字典
Dictionary<String, Int32> outputDictionary = new Dictionary<String, Int32>();
outputDictionary.Add("MyFirstValue", 1);
outputDictionary.Add("MySecondValue",2);
outputDictionary.Add("MyThirdValue", 10);
outputDictionary.Add("MyFourthValue", 20);
outputDictionary.Add("MyFifthValue", 5);
我使用了 3 种方法按值排序
方法一:
outputDictionary = outputDictionary.OrderBy(key => key.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
方法二:
foreach (KeyValuePair<String, String> item in outputDictionary.OrderBy(key => key.Value))
{
// do something with item.Key and item.Value
}
方法三:
outputDictionary = (from entry in outputDictionary orderby entry.Value ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
但无论我选择什么方法,我都会得到结果
MyFirstValue, 1
MyThirdValue, 10
MySecondValue, 2
MyFourthValue, 20
MyFifthValue, 5
随心所欲
MyFirstValue, 1
MySecondValue, 2
MyFifthValue, 5
MyThirdValue, 10
MyFourthValue, 20