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

ief*_*fpw 6 c# linq

List<string> _words喜欢

"Car", "Car", "Car", "Bird", "Sky", "Sky"
Run Code Online (Sandbox Code Playgroud)

我希望按每个字数递减来排序,以便最终List<string>得到

"Car",
"Sky",
"Bird
Run Code Online (Sandbox Code Playgroud)

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

在SQL中这将是:

select word, count(1) as count1
from word
group by word
order by count1 desc, word
Run Code Online (Sandbox Code Playgroud)

回答

另一个变种:

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

Mic*_*x2a 8

你需要使用的组合GroupByOrderByDescending:

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