Kritner Kritner - 1 month ago 14
C# Question

Refactor foreach loop to List<T>.ForEach(...)

Given:

foreach (var obj in _data)
{
maxRows++;
foreach (var param in obj.Parameters)
maxRows++;
}


I'm trying to convert this into (preferably) one single statement. Not for any reason in particular, just curious if it's easy enough to mentally parse, and if possible.

_data.ForEach(feObj => maxRows++);
_data.ForEach(feObj => feObj.Parameters.ForEach(feParam => maxRows++));


This seems to accomplish the same thing, though it would seemingly be less efficient than the original due to iterating through _data an additional time.

Is there a way to combine the two actions within the two separate lines into a single statement?

Answer

You can do this in the same loop.

_data.ForEach(feObj => 
 {
    maxRows++;
    feObj.Parameters.ForEach(feParam => maxRows++);
 });

Moreover, if you are just adding the count you should do as what @Rob had answered. If any other logic you can put it within the braces.

Comments