Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting words in a collection using LINQ

I have a StringCollection object with 5 words in them. 3 of them are duplicate words. I am trying to create a LINQ query that will count how many unique words are in the collection and output them to to the console. So, for example, if my StringCollection has 'House', 'Car', 'House','Dog', 'Cat', then it should output like this:

House --> 2
Car --> 1
Dog --> 1
Cat --> 1

Any ideas on how to create a LINQ query to do this?

like image 707
Icemanind Avatar asked Jun 11 '10 22:06

Icemanind


1 Answers

Try the following

var res = from word in col.Cast<string>()
          group word by word into g
          select new { Word = g.Key, Count = g.Count() };
like image 119
JaredPar Avatar answered Oct 18 '22 20:10

JaredPar