Kritner Kritner - 1 year ago 111
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download