我有一个列表,其中包含一堆可以多次出现的字符串。我想用这个列表并构建一个列表项的字典作为键,它们的出现次数作为值。
例子:
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" );
结果将是一个包含以下内容的字典:
"Peanut Butter", 2
"Jam", 2
"Food", 2
"Snacks", 1
"Philosophy", 1
我有办法做到这一点,但我似乎没有利用 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;
}
最佳答案
您可以使用 C# 中的组子句来执行此操作。
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()
};
如果需要,您也可以直接调用扩展方法:
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);
关于c# - 构建列表中项目计数的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687313/