I am trying to achieve:
foreach (ScheduleItem s in ScheduleItems)
{
foreach (IScheduleModule m in s.ScheduleModules)
{
yield return m;
}
}
using LINQ aggregate and I do not understand why
return ScheduleItems.Aggregate(new Collection<IScheduleModule>(), (x, o) => x.Union(o.ScheduleModules) as Collection<IScheduleModule>);
returns null.
I have no issue using the nested foreach but my instinct was to use aggregate and I don’t understand why it doesn’t produce the same result.
Are there other approaches? What is best in terms of readability and performance?
You should be using
SelectManyfor this:That exactly matches your initial nested foreach loop. It’s also equivalent to this query expression:
(although that will use a slightly different form of
SelectMany).As for why
Aggregateisn’t working: you’re calling Union which returns anIEnumerable<T>, but then usingasto try to convert it toCollection<T>. The result ofUnionwon’t be aCollection<T>, hence the result of theasoperator is null.