我有很多相似的名字的C#列表,我想计算所有单个相似的单词。
示例
假设list具有以下值
one,one,one,two,two,four,four,four然后我想这样计算
one 3
two 2
four 3 我如何从列表中计算这样的值。
发布于 2009-11-27 02:20:46
我会用逗号拆分字符串,遍历所有结果,并将每个单词添加到一个值为1的哈希表或字典中。如果单词(key)已经存在,则递增该值。
string[] values = "one,one,one,two,two,four,four,four".Split(',');
var counts = new Dictionary<string, int>();
foreach (string value in values) {
if (counts.ContainsKey(value))
counts[value] = counts[value] + 1;
else
counts.Add(value, 1);
}或者,如果您愿意,这里有一个LINQ解决方案
var counts = values.GroupBy<string, string, int>(k => k, e => 1)
.Select(f => new KeyValuePair<string, int>(f.Key, f.Sum()))
.ToDictionary(k => k.Key, e => e.Value); 发布于 2009-11-27 02:24:34
这是一个基于Linq的解决方案:
string s = "one,one,one,two,two,four,four,four";
List<string> list = s.Split(',').ToList();
Dictionary<string, int> dictionary = list.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
foreach (var kvp in dictionary)
Console.WriteLine("{0}: {1}", kvp.Key, kvp.Value);输出:
one: 3
two: 2
four: 3这种解决方案没有利用公共值是连续的这一事实。如果总是这样,可以编写一个稍微快一点的解决方案,但这对于短列表或项可以按任何顺序出现都很好。
发布于 2009-11-27 02:24:22
Dictionaty<string, int> listCount = new Dictionaty<string, int>();
for (int i = 0; i < yourList.Count; i++)
{
if(listCount.ContainsKey(yourList[i]))
listCount[yourList[i].Trim()] = listCount[yourList[i].Trim()] + 1;
else
listCount[yourList[i].Trim()] = 1;
}https://stackoverflow.com/questions/1805063
复制相似问题