Linq组字符串数组按计数和排序

时间:2014-09-08 04:02:45

标签: c# linq

我有List<string> _words喜欢

"Car", "Car", "Car", "Bird", "Sky", "Sky"

我希望按每个单词计数降序对其进行排序,以便最终List<string>

"Car",
"Sky",
"Bird

我如何在LINQ中执行此操作?我真的不需要每个单词的计数

SQL中的

将是:

select word, count(1) as count1
from word
group by word
order by count1 desc, word

答案

另一种变体:

    var _output = from p in _words
                  group p by p into g
                  orderby g.Count() descending, g.Key ascending 
                  select g.Key;

2 个答案:

答案 0 :(得分:7)

您需要使用GroupByOrderByDescending的组合:

string[] words = {"Car", "Car", "Car", "Bird", "Sky", "Sky"};
var output = words
    .GroupBy(word => word)
    .OrderByDescending(group => group.Count())   
    .Select(group => group.Key);

答案 1 :(得分:4)

您可以使用GroupBy()然后OrderByDescending()按照从最常见的次数开始的次数排序:

var result = _words.GroupBy(x => x)
                   .OrderByDescending(x => x.Count())
                   .Select(x => x.Key)
                   .ToList();