Adding object variables from a list

Viewed 38

the objects belong to a list which calls an external object class

I would like to simplify the following line of code

int TotalObjectVarN3 = (Object1.variable3 + Object2.variable3 + Object3.variable3 + Object3.variable3);
3 Answers

This overload of System.Linq.Enumerable.Sum should work nicely for you:

Computes the sum of the sequence of Int32 values that are obtained by invoking a transform function on each element of the input sequence.

In this case, the "transform function" would be a Func<TSource, Int32> that returns the value of the variable3 property for the item (e.g. obj => obj.variable3).

You could use it like this:

int TotalObjectVarN3 = new []{ Object1, Object2, Object3 }.Sum(obj => obj.variable3);

This one does it using LINQ

int TotalObjectVarN3 = MyList.Sum(o => o.variable3):

Related