List< string>简单的分组和计数? [英] List<string> Simple Group and Count?

查看:125
本文介绍了List< string>简单的分组和计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 List< string> 设置,其中每个项目包含很多单个字符(即 foreach 会显示为"a","k","p等)

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?

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

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

推荐答案

(鉴于每个条目都是单个字符,是否有任何原因使您没有 List< char> 方式?)

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

这篇关于List&lt; string&gt;简单的分组和计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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