axings
axings

Reputation: 133

Nested Linq Queries doesn't behave as expected

My question is very simple, given following piece of code at the beginning

var list = new[] {
    new { name = "lixiang", age = 14 },
    new { name = "lixiang", age = 16 },
    new { name = "lidian", age = 14 }
};
var people = list.GroupBy(x => x.name);

This would give me a compiler error as expected since people is a Group of records:

var x1 = people.Select(x => x.name);

But what I don't understand is, why this one successfully compile?

var x2 = people.Select(x => x.Select(y => y.name));

Upvotes: 1

Views: 65

Answers (1)

cdhowie
cdhowie

Reputation: 169153

people is an IEnumerable<IGrouping<string, A'>>, where A' is your anonymous type. IGrouping<string, A'> has no name property, which is why the first select fails.

However, x in the second example is IGrouping<string, A'>, which inherits IEnumerable<A'>. This makes y typed as A', which does have a name property. This is why the second example compiles fine.

Note that x2 will have the type IEnumerable<IEnumerable<string>>. To flatten this, change the outer Select to SelectMany:

var x3 = people.SelectMany(x => x.Select(y => y.name));

In this example, x3 will have the type IEnumerable<string>.

This is all academic, of course, since people.Select(x => x.name) would be a much faster way to get the same result (assuming that ordering is not significant).

Upvotes: 2

Related Questions