我想弄清楚如何对字典进行排序,如下所示:
public Dictionary<string, ParseObject> dict = new Dictionary<string, ParseObject>();
ParseObject中有一些字段:
objectId,名称,日期
我可以这样: dict.Get(&#34;日期&#34)
日期内的数据如下所示: 20141028201007
现在,我想对日期字段中的字典重新排序/排序,无论是升序还是降序,但不知道如何做到这一点?
我看过这个:
// Example dictionary.
var dictionary = new Dictionary<string, int>(5);
dictionary.Add("cat", 1);
dictionary.Add("dog", 0);
dictionary.Add("mouse", 5);
dictionary.Add("eel", 3);
dictionary.Add("programmer", 2);
// Order by values.
// ... Use LINQ to specify sorting by value.
var items = from pair in dictionary
orderby pair.Value ascending
select pair;
// Display results.
foreach (KeyValuePair<string, int> pair in items)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
// Reverse sort.
// ... Can be looped over in the same way as above.
items = from pair in dictionary
orderby pair.Value descending
select pair;
但这并非基于对象......
希望有人可以帮助或指导我朝着正确的方向前进,并提前感谢。
答案 0 :(得分:2)
这样可以解决问题:
var dictionary = new Dictionary<string, int>(5);
dictionary.Add("cat", 1);
dictionary.Add("dog", 0);
dictionary.Add("mouse", 5);
dictionary.Add("eel", 3);
dictionary.Add("programmer", 2);
var orderedPairs = dictionary.OrderBy(pair => pair.Value);
foreach (var pair in orderedPairs)
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
基本上,您会收到一个有序的IEnumerable<KeyValuePair<string, int>>
。
使用更复杂的对象:
var dict = new Dictionary<string, ParseObject> { ... };
var orderedPairs = dict.OrderBy(pair => pair.Value.Date);