Reputation: 597
Say I have this array of objects:
var input = new object[]
{
"Hello",
123,
true,
"Hats",
12,34,
'!'
};
Which I then want to group by types and then return a dictionary with the type as the key and the number of occurrences of each type as the value. How would I go about doing this? I've got the array into a dictionary now, but from here I'm a little stuck as to what to do with it.
Upvotes: 0
Views: 218
Reputation: 101701
Simply group by Type
, and use ToDictionary
method:
input.GroupBy(x => x.GetType()).ToDictionary(x => x.Key, x => x.Count());
Usually, when you are using GroupBy
to group based on a reference type you need either override Equals
and GetHashCode
method on the type, or implement a custom comparer to get the expected behaviour. But fortunutely, the Type
class is already doing that. So this will work as expected.
Upvotes: 5