C# List<string> 简单组和计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9702693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:28:18  来源:igfitidea点击:

List<string> Simple Group and Count?

c#linq-group

提问by tripbrock

I have a very simple List<string>setup which contains lots of single characters per item (IE a foreachwould console out to "a" "k" "p" etc)

我有一个非常简单的List<string>设置,其中每个项目包含许多单个字符(即 aforeach将控制台输出为“a”“k”“p”等)

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.

如果有帮助,我正在使用 .Net 4。

回答by Jon Skeet

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

(鉴于每个条目都是一个字符,List<char>顺便说一下,您是否有任何理由没有?)

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.

请注意,这在内部表示方面有些低效。你绝对可以“手动”更有效地完成它,但它也需要更多的工作。除非你的名单很大,否则我会坚持这一点。

回答by Viacheslav Smityukh

The easiest way to do this is the Linq using

最简单的方法是使用 Linq

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;
}

回答by Scroog1

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()));