2

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);
1
  • 1
    If the objects were in a collection (e.g. a List<MyClass>), you can use LINQ: myCollection.Sum(o => o.variable3) or a corresponding loop Commented Nov 13, 2021 at 11:50

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

This one does it using LINQ

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.