Kritner Kritner - 4 months ago 50
C# Question

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


foreach (var obj in _data)
foreach (var param in obj.Parameters)

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?


You can do this in the same loop.

_data.ForEach(feObj => 
    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.