Counting words in a collection using LINQ

I have a StringCollection object with 5 words in them. 3 of them are repeating words. I am trying to create a LINQ query that will count the number of unique words in a collection and print them to the console. So, for example, if my StringCollection has "House", "Car", "House", "Dog", "Cat", then it should be displayed as follows:

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

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

+7
c # linq
source share
7 answers

Try to execute

var res = from word in col.Cast<string>() group word by word into g select new { Word = g.Key, Count = g.Count() }; 
+11
source share
 var xs = new StringCollection { "House", "Car", "House", "Dog", "Cat" }; foreach (var g in xs.Cast<string>() .GroupBy(x => x, StringComparer.CurrentCultureIgnoreCase)) { Console.WriteLine("{0}: {1}", g.Key, g.Count()); } 
+4
source share

Given that you use StringCollection and want to ignore case, you will need to use Enumerable.GroupBy with Enumerable.Cast :

 var results = collection.Cast<string>.GroupBy( i => i, (word, words) => new { Word = word, Count = words.Count() }, StringComparer.CurrentCultureIgnoreCase ); foreach(var wordPair in results) Console.WriteLine("Word: \"{0}\" - Count: {1}", wordPair.Word, wordPair.Count); 
+1
source share

To create a single row result ...

 var stringCollection = new[] { "House", "Car", "house", "Dog", "Cat" }; var result = stringCollection.Cast<string>().GroupBy( k => k, StringComparer.InvariantCultureIgnoreCase) .Select(v => v.Key + " -->" + v.Count()) .Aggregate((l,r)=>l+" " + r); //result = "House -->2 Car -->1 Dog -->1 Cat -->1" 

To put each value on a different line ...

 var stringCollection = new[] { "House", "Car", "house", "Dog", "Cat" }; var result = stringCollection.Cast<string>().GroupBy( k => k, StringComparer.InvariantCultureIgnoreCase); foreach (var value in result) Console.WriteLine("{0} --> {1}", value.Key, value.Count()); 
+1
source share
 foreach(var g in input.GroupBy(i => i.ToLower()).Select(i => new {Word = i.Key, Count = i.Count()}) { Console.WriteLine(string.Format("{0} -> {1}", g.Word, g.Count)); } 
0
source share

It should be simple:

 Console.WriteLine(stringCollection.Distinct().Count()); 
0
source share
 var query = from s in Collection group s by s.Description into g select new {word = g.Key, num = g.Count()}; 
0
source share

All Articles