简体   繁体   中英

Linq group string array by count and sort

I have a List<string> _words like

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

I want to sort it by each word count descending so the final List<string> would be

"Car",
"Sky",
"Bird

how do I do this in LINQ? I don't really need the count for each word

in SQL this would be:

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

Answer

Another variant:

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

You'll need to use a combination of GroupBy and OrderByDescending :

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

You can use GroupBy() then OrderByDescending() to order by number of occurrence starting from the most frequent :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM