我有一个包含以下结果的数组
red
red
red
blue
blue
Green
White
Grey
我希望获得数组的每个值的重复计数,例如:
red Count=3
blue Count=2
Green Count=1
White Count=1
Grey Count=1
答案 0 :(得分:33)
LINQ让这一切变得简单:
Dictionary<string, int> counts = array.GroupBy(x => x)
.ToDictionary(g => g.Key,
g => g.Count());
答案 1 :(得分:1)
将它们添加到词典中:
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach(string s in list)
{
int prevCount;
if (!counts.TryGet(s, out prevCount))
{
prevCount.Add(s, 1);
}
else
{
counts[s] = prevCount++;
}
}
然后count包含字符串作为键,以及它们作为值出现。
答案 2 :(得分:1)
嗯这是一项非常艰巨的任务,但Captain Algorithm会帮助你!他告诉我们,有很多方法可以做到这一点。其中一个他给我,我把它给你:
Dictionary <object, int> tmp = new Dictionary <object, int> ();
foreach (Object obj in YourArray)
if (!tmp.ContainsKey(obj))
tmp.Add (obj, 1);
else tmp[obj] ++;
tmp.Values;//Contains counts of elements
答案 3 :(得分:1)
上面有点错误, 正确的代码是:
string[] arr = { "red", "red", "blue", "green", "Black", "blue", "red" };
var results = from str in arr
let c = arr.Count( m => str.Contains(m.Trim()))
select str + " count=" + c;
foreach(string str in results.Distinct())
Console.WriteLine(str);
答案 4 :(得分:0)
制作另一个计数数组....并在原始数组上循环,条件是如果它发现红色递增计数数组的第一个单元格......如果它发现蓝色递增计数数组中的第二个单元格。 ...等等。 祝你好运。
答案 5 :(得分:0)
Hashtable ht = new Hashtable();
foreach (string s in inputStringArray)
{
if (!ht.Contains(s))
{
ht.Add(s, 1);
}
else
{
ht[s] = (int)ht[s] + 1;
}
}
答案 6 :(得分:-1)
我认为这应该可以解决问题
string[] arr = { "red", "red", "blue", "green", "Black", "blue", "red" };
var results = from str in arr
let c = arr.Count( m => str.Contains(m.Trim()))
select str + " count=" + str;
foreach(string str in results.Distinct())
Console.WriteLine(str);
输出:
red count=3
blue count=2
green count=1
Black count=1