I have a class Counter that counts things by key. Simplified:
public class Counter<T> {
private Dictionary<T, int> counts;
public void Increment(T key) {
int current;
bool exists = counts.TryGetValue(key, out current);
if (exists) {
counts[key]++;
} else {
counts[key] = 1;
}
}
}
It does a number of other things specialized to my needs, but that's the essence. So far, it works great.
Now I want to enable it to be used in a Linq query (with both the keys and the values). Do to that, I think I need to implement
IEnumerable<T, int>
So I added:
public class Counter<T> : IEnumerable<KeyValuePair<T, int>> {
// ...
IEnumerator<KeyValuePair<T, int>>
IEnumerable<KeyValuePair<T, int>>.GetEnumerator()
{
return ((IEnumerable<KeyValuePair<T, int>>)counts).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return counts.GetEnumerator();
}
Which unfortunately leads to the compiler error
The number of generic arguments provided doesn't equal the arity of the generic type definition. Parameter name: instantiation
Questions
UPDATE: Typo
I had a typo while simplifying my code to post. The code is in fact attempting to implement IEnumerable<KeyValuePair<T, int>>
and not IEnumerable<T, int>
counts
dictionary that you modify, which is a side effect.Here is how you can get item counts by key:
var counters = keyedData
.GroupBy(item => item.MyKey)
.ToDictionary(g => g.Key, g => g.Count());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With