List Simple Group and Count?

2019-01-24 06:35发布

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.

标签: c# linq-group
3条回答
放荡不羁爱自由
2楼-- · 2019-01-24 07:23

(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.

查看更多
戒情不戒烟
3楼-- · 2019-01-24 07:25
var list = new[] {"a", "t", "t", "y", "a", "y", "y", "t"};
var result = (from item in list
              group item by item into itemGroup
              select String.Format("{0} - {1}", itemGroup.Key, itemGroup.Count()));
查看更多
▲ chillily
4楼-- · 2019-01-24 07:35

The easiest way to do this is the Linq using

var list = new[] { "a", "a", "b", "c", "d", "b" };
var grouped = list
    .GroupBy(s => s)
    .Select(g => new { Symbol = g.Key, Count = g.Count() });

foreach (var item in grouped)
{
    var symbol = item.Symbol;
    var count = item.Count;
}
查看更多
登录 后发表回答