Refactoring nested foreach statement

The obvious solution is to flatten into methods.

Old:

void SubmitOrders()
{
    var orders = GetOrders();
    foreach (Order o in orders)
    {
        foreach (OrderDetail d in o.Details)
        {
            // Blah...
        }
    }
}

New:

void SubmitOrders()
{
    var orders = GetOrders()
    foreach (Order o in orders)
    {
        SubmitOrder(o);
    }
}

void SubmitOrder(Order order)
{
    foreach (OrderDetail d in order.Details)
    {
        // Blah...
    }
}

Other answers here seem to be focused on Linq, and I would agree that if your loops have no side-effects (i.e. you are just trying to extract some information from the innermost loop), then you can probably rewrite the entire thing using one or two simple Linq statements. If side-effects are involved, then just follow the time-tested practice of subroutines.


You're going to have to be more specific about what you mean regarding "more elegant", as IMO there's nothing particularly inelegant about a nested foreach.

That being said, the LINQ extension methods in .NET 3.5 and above can help out (specifically SelectMany).

public class Foo
{
    public List<string> Strings { get; set; }
}

...

List<Foo> foos = new List<Foo>();

foreach(string str in foos.SelectMany(f => f.Strings))
{
    ...
}

Tags:

C#