Search code examples
c#linqienumerableigrouping

Why can't I return an IEnumerable<IGrouping<A,B>> as an IEnumerable<IEnumerable<B>>


I've used GroupBy(), and produced an IEnumerable<IGrouping<TKey,TValue>>.

And I can foreach over it, and pass each element (each IGrouping<TKey,TValue>) into a method that accepts IEnumerable<TValue>

This is unsurprising - IGrouping<TKey,TValue> implements IEnumerable<TValue>

But if I define a method that accepts IEnumerable<IEnumerable<B>>, then I can't directly pass in the output of GroupBy(), even though it is an IEnumerable<> and every element inside it is an IEnumerable<B>

Why?


Solution

  • As pointed out by several people (and indeed, as I sort of knew in the back of my head) this is simply a covariance issue, and only breaks in a pre-.NET 4 environment.