简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM