列表数组重复计数

我有一个包含以下结果的数组

red red red blue blue Green White Grey 

我希望获得数组的每个值的重复计数,例如:

 red Count=3 blue Count=2 Green Count=1 White Count=1 Grey Count=1 

LINQ让这很简单:

 Dictionary counts = array.GroupBy(x => x) .ToDictionary(g => g.Key, g => g.Count()); 

将它们添加到词典:

 Dictionary counts = new Dictionary(); foreach(string s in list) { int prevCount; if (!counts.TryGet(s, out prevCount)) { prevCount.Add(s, 1); } else { counts[s] = prevCount++; } } 

然后count包含字符串作为键,以及它们作为值出现。

嗯这是一项非常艰巨的任务,但Captain Algorithm会帮助你! 他告诉我们,有很多方法可以做到这一点。 其中一个他给我,我给你:

 Dictionary  tmp = new Dictionary  (); foreach (Object obj in YourArray) if (!tmp.ContainsKey(obj)) tmp.Add (obj, 1); else tmp[obj] ++; tmp.Values;//Contains counts of elements 

上面有一点错误,正确的代码是:

 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); 

制作另一个计数数组….并在原始数组上循环,条件是如果它发现红色递增计数数组的第一个单元格…如果它发现蓝色递增计数数组中的第二个单元格….等等 祝好运 。

 Hashtable ht = new Hashtable(); foreach (string s in inputStringArray) { if (!ht.Contains(s)) { ht.Add(s, 1); } else { ht[s] = (int)ht[s] + 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