what is the way to declare function like php array_count_values in c#?
i want to declare function in c# that accept an array an return the Counts all the values of this a开发者_如何学Crray
like array_count_values in php
$array = array(1, 1, 2, 3, 3, 5 );
return
Array
(
[1] => 2
[2] => 1
[3] => 2
[5] => 1
)
what is the efficient way to do this ?
thanks
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);
}
Alternatively, you can get a Dictionary<int, int>
like so:
int[] array = new[] { 1, 1, 2, 3, 3, 5 };
var counts = array.GroupBy(x => x)
.ToDictionary(g => g.Key, g => g.Count());
Edit
Sorry, I see now that my previous answer was not correct. You are wanting to count each type of unique value.
You can use a Dictionary to store the value types:
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;
}
If you want to be able to count something besides ints try this
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;
}
精彩评论