Reputation: 43
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);
Upvotes: 2
Views: 53
Reputation: 18016
Using Select
is an option followed by the Sum
method. Select Projects each element of a sequence into a new form.
list.Select(i => i.variable3).Sum();
More about Select
- https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=net-5.0
Upvotes: 0
Reputation: 43
This one does it using LINQ
int TotalObjectVarN3 = MyList.Sum(o => o.variable3):
Upvotes: 0
Reputation: 112815
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);
Upvotes: 2