Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce multiple nested foreach blocks

I have the following scenario:

var Ids = object1.GetIds(); // returns IEnumerable<int>
foreach (var id in Ids)
{
    foreach (var relatedObject in object1.GetRelatedObjects(id))
    {
    // Do Something with related object
    }
}

In this case, i want to get rid of from the first foreach and reduce this logic into single foreach. How could i achieve this?

Should it be possible with LINQ expression some similar methodology?

like image 477
Akiner Alkan Avatar asked Oct 17 '25 03:10

Akiner Alkan


1 Answers

When there is nothing between the two loops, before or after the nested one, you can use SelectMany to "flatten" two loops into one:

foreach (var relatedObject in Ids.SelectMany(object1.GetRelatedObjects)) {
    ...
}

One major difference between this loop and the loop that you have is that id is no longer in scope. Assuming that relatedObject exposes a public Id property, this should not be a problem in your situation, because you could extract the id back with

var id = relatedObject.Id;
like image 59
Sergey Kalinichenko Avatar answered Oct 19 '25 16:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!