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 very simple List<string> setup which contains lots of single characters per item (IE a foreach would console out to "a" "k" "p" etc)

What I'd like to do is be able to group the items and also count how many of each occurs so I'd get an output similar to:

a - 2
t - 3
y - 3

Any tips on the best way to do this?

I am using .Net 4 if that's any help.

See Question&Answers more detail:os

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

1 Answer

(Given that each entry is a single character, is there any reason you don't have a List<char> by the way?)

How about:

// To get a Dictionary<string, int>
var counts = list.GroupBy(x => x)
                 .ToDictionary(g => g.Key, g => g.Count());

// To just get a sequence
var counts = list.GroupBy(x => x)
                 .Select(g => new { Text = g.Key, Count = g.Count() });

Note that this is somewhat inefficient in terms of internal representation. You could definitely do it more efficiently "manually", but it would also take more work. Unless your list is large, I would stick to this.


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