使用linq对不同的唯一出现次数进行排序

时间:2012-04-23 15:21:12

标签: c# linq

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

ghj
def
abc
def
abc
abc

为:

abc
def
ghj

我正在寻找lambda表达式。

2 个答案:

答案 0 :(得分: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() ...

答案 1 :(得分:2)

如果要获取按出现次数排序的不同列表,请使用分组依据:

var query = foo.GroupBy(xx => xx)
               .OrderByDescending(gg => gg.Count())
               .Select(gg => gg.Key);
// on your input returns:
// abc
// def
// ghj