How to reduce the number of 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 the first foreach and reduce that logic into a single foreach. How can I achieve this?
Can a similar methodology be used with a LINQ expression?
source to share
If there is nothing between the two loops, before or after the nested one, you can use SelectMany
to "smooth" two loops into one:
foreach (var relatedObject in Ids.SelectMany(object1.GetRelatedObjects)) {
...
}
One significant difference between this loop and the loop you have is that it is id
no longer in scope. Assuming it relatedObject
provides a public property id
, this shouldn't be a problem in your situation, because you can fetch id
back with
var id = relatedObject.Id;
source to share
Personally, I like to make full use of the extra curly braces / block for loops foreach
.
You cannot reduce the complexity. But you can make it more enjoyable.
IEnumerable<int> Ids = object1.GetIds()
foreach (var id in Ids)
foreach (var relatedObject in object1.GetRelatedObjects(id))
{
DoSomething(relatedObject);
}
source to share