建设项目数的词典列表中 [英] Building a dictionary of counts of items in a list
问题描述
我有一个包含一串字符串,可以出现多次的List。我想借这个名单,并建立列表项为重点和它们的出现为价值的计数的字典
例如:
列表<串GT;东西=新的List<串GT;();
stuff.Add(花生酱);
stuff.Add(大灌篮);
stuff.Add(食品);
stuff.Add(小吃);
stuff.Add(哲学);
stuff.Add(花生酱);
stuff.Add(大灌篮);
stuff.Add(食品);
和结果将是包含字典:
花生酱,2
大灌篮,2
民以食为天,2
小吃,1
哲学,1
我有办法做到这一点,但它似乎并不像我利用好东西用C#m的3.0
公众解释<字符串,整数> CountStuff(IList的<串GT; stuffList)
{
&字典LT;字符串,整数> stuffCount =新词典<字符串,整数>();
的foreach(在stuffList串的东西){
//初始化或增加计数此项目
如果(stuffCount.ContainsKey(东西)){
stuffCount [东东] ++;
}其他{
stuffCount.Add(东东,1);
}
}
返回stuffCount;
}
您可以使用group子句。在C#中做到这一点。
列表<串GT;东西=新的List<串GT;();
...
组VAR =从s的东西组由s s转换g选择
{新东西= g.Key,计数= g.Count()};
您可以调用扩展方法直接,以及如果你想:
VAR组= stuff.GroupBy(S = GT S)。选择(
S =>新建{东西= s.Key,计数= S .Count之间的()});
从这里它是一个短的一跳将其放入一个词典<字符串, INT>
:
VAR词典= groups.ToDictionary(G => g.Stuff,G = GT; 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屋!