Linq group string array by number and sort

I have List<string> _wordshow

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

I want to sort it by each number of words going down, so the final List<string>will be

"Car",
"Sky",
"Bird

How to do it in LINQ? I don't need a score for every word

in SQL, it will 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;
+4
source share
2 answers

You will need a combination of GroupByand OrderByDescending:

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

You can use GroupBy(), then OrderByDescending()to order by the number of cases, starting with the most frequent:

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

All Articles