How can I use LINQ to avoid nested loops?

Skywise picture Skywise · Nov 28, 2011 · Viewed 7.1k times · Source

I've been reading about LINQ to Objects, and now my colleagues want me to present it to them.

Now, I have an OK understanding of the operators and the syntax choices, but I've heard you can avoid heavy nested loops by using LINQ. I'm having trouble coming up with a good set of "before and after" code listings to demonstrate this though.

I found a great example of sorting and grouping with and without LINQ in Magennis' book, and he also has an example of writing xml. But what about those nested loops? Is this even a realistic claim, given that we usually need a foreach loop or two to iterate over the results of the query anyway?

If anyone can explain this idea to me (ideally with specific examples), I would greatly appreciate it.

Answer

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Nov 28, 2011

Here's a type of nested loop you can remove with Linq.

foreach(SomeClass item in Items)
{
    foreach(SomeOtherClass subItem in item.SubItems)
    {
        // ...
    }
}

It can be turned into:

foreach(SomeOtherClass subItem in Items.SelectMany(i => i.SubItems))
{
}

Using the SelectMany extension method on IEnumerable.

One place where this is quite useful is for nested loop double-break scenarios.