2010-11-18 50 views

回答

4
int[] array = new[] { 1, 1, 2, 3, 3, 5 }; 
var counts = array.GroupBy(x => x) 
        .Select(g => new { Value = g.Key, Count = g.Count() }); 
foreach(var count in counts) { 
    Console.WriteLine("[{0}] => {1}", count.Value, count.Count); 
} 

或者,你可以得到一个Dictionary<int, int>像这样:

int[] array = new[] { 1, 1, 2, 3, 3, 5 }; 
var counts = array.GroupBy(x => x) 
        .ToDictionary(g => g.Key, g => g.Count()); 
+0

这不是一个单一功能的答案 - 不存在 - 但它比我准备的循环更好。 +1 – Randolpho 2010-11-18 19:54:37

+0

谢谢,我怎么能在这个数组结果中找到最大count.count? – 2010-11-18 20:06:33

+0

var maxValue = counts.Max(g => g.Value); – mellamokb 2010-11-19 14:28:52

1

编辑

对不起,我现在看到我以前的答案是不正确的。你想要计算每种类型的唯一值。

您可以使用字典来存储值类型:

object[] myArray = { 1, 1, 2, 3, 3, 5 }; 
Dictionary<object, int> valueCount = new Dictionary<object, int>(); 
foreach (object obj in myArray) 
{ 
    if (valueCount.ContainsKey(obj)) 
     valueCount[obj]++; 
    else 
     valueCount[obj] = 1; 
} 
0

如果你希望能够算除了ints之外,还有其他的东西试试这个

public static Dictionary<dynamic, int> Count(dynamic[] array) 
    { 

    Dictionary<dynamic, int> counts = new Dictionary<dynamic, int>(); 

    foreach(var item in array) { 

    if (!counts.ContainsKey(item)) { 
    counts.Add(item, 1); 
    } else { 
    counts[item]++; 
    } 


    } 

    return counts;  
    } 
相关问题