Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq group string array by count and sort

Tags:

c#

linq

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;
like image 725
iefpw Avatar asked Sep 08 '14 04:09

iefpw


2 Answers

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);
like image 84
Michael0x2a Avatar answered Oct 18 '22 17:10

Michael0x2a


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();
like image 39
har07 Avatar answered Oct 18 '22 17:10

har07