3

我想知道如何使用 linq 按出现次数最多的降序对以下列表进行排序:

ghj
def
abc
def
abc
abc

到:

abc
def
ghj

我正在寻找 lambda 表达式。

4

2 回答 2

5
string[] names = { "ghj", "def", "abc", "def", "abc", "abc" };

IEnumerable<string> query = names
   .GroupBy(s=>s) // groups identical strings into an IGrouping
   .OrderByDescending( group => group.Count()) // IGrouping is a collection, so you can count it
   .Select(group=>group.Key); // IGrouping has a Key, which is the thing you used to group with. In this case group.Key==group.First()==group.skip(1).First() ...
于 2012-04-23T15:29:37.970 回答
2

如果要获取按出现次数排序的不同列表,请使用 Group By:

var query = foo.GroupBy(xx => xx)
               .OrderByDescending(gg => gg.Count())
               .Select(gg => gg.Key);
// on your input returns:
// abc
// def
// ghj
于 2012-04-23T15:30:05.340 回答