什么是在c#中声明像php array_count_values这样的函数的方法?

时间:2010-11-18 19:42:44

标签: c# arrays count

我想在c#中声明接受数组的函数 返回Counts这个数组的所有值

类似于php中的array_count_values

$array = array(1, 1, 2, 3, 3, 5 );

return 

Array
(
    [1] => 2
    [2] => 1
    [3] => 2
    [5] => 1
)

这样做的有效方法是什么?

感谢

3 个答案:

答案 0 :(得分: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());

答案 1 :(得分:1)

修改

抱歉,我现在看到我之前的回答不正确。您想要计算每种类型的唯一值。

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

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

答案 2 :(得分:0)

如果你想能够计算除了整数之外的东西,试试这个

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