建立列表中项目计数的字典 [英] Building a dictionary of counts of items in a list
本文介绍了建立列表中项目计数的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
列表< string> stuff = new List< string>();
stuff.Add(花生酱);
stuff.Add(Jam);
stuff.Add(食物);
stuff.Add(Snacks);
stuff.Add(哲学);
stuff.Add(花生酱);
stuff.Add(Jam);
stuff.Add(食物);
,结果将是一个字典,包含:
pre>
花生酱,2
果酱,2
食物,2
小吃,1
哲学,1
我有办法做到这一点,但似乎不像我'使用C#3.0中的好东西
public Dictionary< string,int> CountStuff(IList< string> stuffList)
{
字典< string,int> stuffCount = new Dictionary< string,int>();
foreach(string stuff in stuffList){
//初始化或增加此项的计数
if(stuffCount.ContainsKey(stuff)){
stuffCount [东西] ++;
} else {
stuffCount.Add(stuff,1);
}
}
返回stuffCount;
}
解决方案
在C#中执行此操作。
列表< string> stuff = new List< string>();
...
var groups =从s组中的s通过s选择
new {Stuff = g.Key,Count = g.Count()};
如果需要,您也可以直接调用扩展方法:
var groups = stuff.GroupBy(s => s).Select(
s => new {Stuff = s.Key,Count = s .Count()});
从这里,这是一个短跳到一个 Dictionary< string, int>
:
var dictionary = groups.ToDictionary(g => g.Stuff,g = g.Count);
I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count of their occurrences as the value.
Example:
List<string> stuff = new List<string>();
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
stuff.Add( "Snacks" );
stuff.Add( "Philosophy" );
stuff.Add( "Peanut Butter" );
stuff.Add( "Jam" );
stuff.Add( "Food" );
and the result would be a Dictionary containing:
"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1
I have a way to do this, but it doesn't seem like I'm utilizing the good stuff in C# 3.0
public Dictionary<string, int> CountStuff( IList<string> stuffList )
{
Dictionary<string, int> stuffCount = new Dictionary<string, int>();
foreach (string stuff in stuffList) {
//initialize or increment the count for this item
if (stuffCount.ContainsKey( stuff )) {
stuffCount[stuff]++;
} else {
stuffCount.Add( stuff, 1 );
}
}
return stuffCount;
}
解决方案
You can use the group clause in C# to do this.
List<string> stuff = new List<string>();
...
var groups = from s in stuff group s by s into g select
new { Stuff = g.Key, Count = g.Count() };
You can call the extension methods directly as well if you want:
var groups = stuff.GroupBy(s => s).Select(
s => new { Stuff = s.Key, Count = s.Count() });
From here it's a short hop to place it into a Dictionary<string, int>
:
var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);
这篇关于建立列表中项目计数的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文