Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a list that contains only strings. What I would love to do is group by and return a count.

For instance:

Foo1
Foo2
Foo3
Foo1
Foo2 
Foo2

Would result in Foo1: 2, Foo2: 3, Foo3: 1. I've tried with Linq but the list has a GroupBy that might do the trick but i messed it up, can't figure the use :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

var list = new List<string> { "Foo1", "Foo2", "Foo3", "Foo2", "Foo3", "Foo3", "Foo1", "Foo1" };

var grouped = list
    .GroupBy(s => s)
    .Select(group => new { Word = group.Key, Count = group.Count() });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...