C#列表<串GT;简单集团和计数? [英] C# List<string> Simple Group and Count?

查看:99
本文介绍了C#列表<串GT;简单集团和计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的列表设置,其中包含了大量的每件单字符(即一个foreach会安慰到AKP等)

I have a very simple List 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:

一 - 2
T - 3

a - 2 t - 3 y - 3

在做到这一点的最好办法任何提示

Any tips on the best way to do this?

我使用.NET 4中,如果这是任何帮助。

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

推荐答案

(假设每个条目是单个字符,没有任何理由,你没有一个列表<焦炭> 的方式)

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

怎么样?

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

这篇关于C#列表&LT;串GT;简单集团和计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆