简体   繁体   English

如何按值列表中的某个元素对Dictionary <string,List <int >>进行排序?

[英]How to sort a Dictionary<string, List<int>> by a certain element in values list?

I have a dictionary which holds strings as keys and Lists as values. 我有一个字典,它将字符串作为键,列表作为值。 Imagine you have Olympic Games where the keys are different countries and the values in each list are for example number of participants, number of sports, gold medals, silver medals, etc. So if I want to sort the countries by gold medals and say gold medals is the second entry in each list I would want something like this: 想象一下,你有奥运会的关键是不同的国家,每个名单中的价值观是参与人数,体育项目数,金牌,银牌等。所以,如果我想用金牌对国家进行排序并说金牌奖牌是每个列表中的第二个条目我想要这样的东西:

var countryRankings = new Dictionary<string, List<int>>();
countryRankings.Add(country, new List<int>() {numberOfParticipants, numberOfWins });
//some more country data follows
countryRankings.OrderByDescending(pairs => pairs.Value[1]);

The last bit is not rejected by VisualStudio but is not working as expected. VisualStudio不会拒绝最后一位,但是没有按预期工作。 The dictionary is not sorted.When I think about it it's better to create class country with different properties and then sort with Lambda in the way OrderBy(c => c.goldMedals) but is there a way to do this with nested inside a dictionary List ? 字典没有排序。当我考虑它时,最好创建具有​​不同属性的类国家,然后按照OrderBy(c => c.goldMedals)的方式使用Lambda排序,但有没有办法在嵌套在字典中的情况下执行此操作清单?

That's because the OrderByDescending extension method does not mutate (modify) the original object ( countryRankings ) but instead returns another object that, when enumerated, produces ordered references to elements in the original dictionary. 这是因为OrderByDescending扩展方法不会改变(修改)原始对象( countryRankings ),而是返回另一个对象,当枚举时,该对象生成对原始字典中元素的有序引用。

So, this should work: 所以,这应该工作:

var orderedRankings = countryRankings.OrderByDescending(pairs => pairs.Value[1]); 
// now you can iterate over orderedRankings
foreach(var rankingPair in orderedRankings)
{
    // do something with it..
}

And, yes it would be better to create a class as you suggested in the last part of the question but that doesn't change the answer. 而且,是的,如你在问题的最后部分所建议的那样创建一个类会更好,但这不会改变答案。

The OrderByDescending method doesn't sort the dictionary, it returns a new collection that is sorted. OrderByDescending方法不对字典进行排序,它返回一个已排序的新集合。

Assign the result to a variable. 将结果分配给变量。 It can't be a dictionary though, as the items in a dictionary can't be reordered. 它不能是字典,因为字典中的项目不能重新排序。 You can use the ToList method to realise the result as an actual collection: 您可以使用ToList方法将结果实现为实际集合:

List<KeyValuePair<string, List<int>>> result =
  countryRankings.OrderByDescending(pairs => pairs.Value[1]).ToList();

Using a class instead of a list of integers would be better, but it doesn't change what you need to do to get the sorted result, only what the expression to sort it looks like. 使用类而不是整数列表会更好,但它不会改变你需要做的事情来获得排序结果,只改变要对它进行排序的表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM