LINQ Aggregate vs. Nested Foreach

I am trying to achieve:

foreach (ScheduleItem s in ScheduleItems)
{
    foreach (IScheduleModule m in s.ScheduleModules)
    {
        yield return m;
    }
}

using LINQ aggregate and I don't understand why

return ScheduleItems.Aggregate(new Collection<IScheduleModule>(), (x, o) => x.Union(o.ScheduleModules) as Collection<IScheduleModule>);

returns null.

I have no problem using a nested foreach, but my instinct was to use an aggregate, and I don’t understand why it does not give the same result.

Are there other approaches? Which is better in terms of readability and performance?

+3
source share
2 answers

You should use SelectManyfor this:

ScheduleItems.SelectMany(s => s.ScheduleModules)

This exactly matches your initial foreach nested loop. This is also equivalent to the expression of this query:

from s in ScheduleItems
from m in s.ScheduleModules
select m

(although this will use a slightly different form SelectMany).

Aggregate : Union, IEnumerable<T>, as Collection<T>. Union Collection<T>, as .

+10

SelectMany? , , .

var results = ScheduleItems.SelectMany(si => si.ScheduleModules);
+2

Source: https://habr.com/ru/post/1717834/


All Articles