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));
peopleis anIEnumerable<IGrouping<string, A'>>, whereA'is your anonymous type.IGrouping<string, A'>has nonameproperty, which is why the first select fails.However,
xin the second example isIGrouping<string, A'>, which inheritsIEnumerable<A'>. This makesytyped asA', which does have anameproperty. This is why the second example compiles fine.Note that
x2will have the typeIEnumerable<IEnumerable<string>>. To flatten this, change the outerSelecttoSelectMany:In this example,
x3will have the typeIEnumerable<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).