Search code examples
c#linqnested-loops

Reduce nested loops using Linq


I was wandering if the following nested loops could be rewritten using linq. The catch here is that you return the "item2" if "value" is contained in a list of "item2".

foreach (var item1 in item1list)
    foreach (var item2 in item1.items2list)
        foreach (var item3 in item2.items3list)
            if (item3 == value)
                return item2;

return null;

Solution

  • Use SelectMany for first 2 loops and FirstOrDefault+Any for the third + the if check:

    return item1list.SelectMany(x1 => x1.items2list)
                    .FirstOrDefault(x2 => x2.items3list.Any(x3 => x3 == value));
    

    You could also replace the Any call with Contains(value).

    Is it more readable? Probably not. Putting your 3 loops in a private method with a descriptive name would probably be better for anybody who reads that code in the future.