List<string> Simple Group and Count?

纵饮孤独 提交于 2019-11-29 03:55:29

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

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;
}
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()));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!