我正在排序一个字典,其中包含值为&的按键。我有一个单词和时间数量的散列,我想按照使用的时间数量排序。C#按值排序字典
有一个SortedList对单个值很有用,我想将它映射回单词。
SortedDictionary按键排序,不是值。
我可以使用自定义类,有没有更好的方法。
我做了一些谷歌搜索,但我无法找到我正在寻找什么。
我正在排序一个字典,其中包含值为&的按键。我有一个单词和时间数量的散列,我想按照使用的时间数量排序。C#按值排序字典
有一个SortedList对单个值很有用,我想将它映射回单词。
SortedDictionary按键排序,不是值。
我可以使用自定义类,有没有更好的方法。
我做了一些谷歌搜索,但我无法找到我正在寻找什么。
我找到了答案
List<KeyValuePair<string, string>> BillsList = aDictionary.ToList();
BillsList.Sort(delegate(KeyValuePair<string, string> firstPair,
KeyValuePair<string, string> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
你可以使用lambda使其更简单。 'BillsList.Sort((firstPair,nextPair)=> firstPair.Value.CompareTo(nextPair.Value));' –
这应做到:
Dictionary<string, string> d = new Dictionary<string, string>
{
{"A","Z"},
{"B","Y"},
{"C","X"}
};
d.OrderBy(x=>x.Value).Select(x=>x.Key);
将返回C,B,A
下面是使用LINQ和计数映射到Word :
IDictionary<string, int> wordsAndCount = new Dictionary<string, int>
{
{"Batman", 987987987},
{"MeaningOfLife",42},
{"Fun",69},
{"Relaxing",420},
{"This", 2}
};
var result = wordsAndCount.OrderBy(d => d.Value).Select(d => new
{
Word = d.Key,
Count = d.Value
});
示例键值对 –
'Dictionary'未按设计排序。排序它没有意义。你打算如何使用它?展示实际示例,我们将尝试找到最优化的集合\解决方案。 –
您需要将您的字典(根据定义,未排序)复制到其他集合(例如列表)中,然后对第二个集合进行排序。看看.Net方法[.toList()](http://www.dotnetperls.com/tolist) – paulsm4