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 ou开发者_运维百科tput like this:
House --> 2 Car --> 1 Dog --> 1 Cat --> 1
Any ideas on how to create a LINQ query to do this?
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() };
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());
}
Given that you are using StringCollection and want to ignore case, you'll 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);
To build a single string value 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());
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));
}
It should be as simple as:
Console.WriteLine(stringCollection.Distinct().Count());
var query =
from s in Collection
group s by s.Description into g
select new {word = g.Key, num = g.Count()};
精彩评论