I have a class defined as
class P
{
public List<P> children;
public int Val1;
public int Val2;
}
As you can see the class has a list of objects of the same class. I instantiate the class and fill the list:
P myp = new P { children = new List<P> {new P {Val1 = 1, Val2 = 1}, new P {Val1 = 2, Val2 = 2}}};
Now, if I want to sum up the values of the children’s fields and place them in the appropriate parent field I can do
foreach (var p in myp.children)
{
myp.Val1 += p.Val1;
myp.Val2 += p.Val2;
}
which seems efficient but uglier or I can do
myp.Val1 = myp.children.Sum(p => p.Val1);
myp.Val2 = myp.children.Sum(p => p.Val2);
which is more readable but iterates through the list twice.
Is there a beautiful AND efficient way of doing this? Or am I stuck with the foreach?
Sometimes we developers get neurotic about the silliest things. I’ve been there way too much. I don’t think there is any reason to change it.
Still, if you want to, here is an idea:
And then you can do…