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);
CodePudding user response:
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);
CodePudding user response:
This one does it using LINQ
int TotalObjectVarN3 = MyList.Sum(o => o.variable3):
CodePudding user response:
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://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=net-5.0