我有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;
答案 0 :(得分:7)
您需要使用GroupBy
和OrderByDescending
的组合:
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();