Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total sum for an object property value in a list using a lambda function [duplicate]

I have the following: List<OutputRow> which contains a number of OutputRow objects.

I am wondering if there is a way for me to use a lambda function on the list to return the total sum of the values of a certain propertyX on each OutputRow object in the list.

Example list:

OutputRow.propertyX = 4  
OutputRow.propertyX = 6  
OutputRow.propertyX = 5  

return 15

like image 565
Baxter Avatar asked Apr 25 '12 13:04

Baxter


People also ask

How do you sum a list in C#?

C# Linq Sum() MethodFind the sum of elements using the Linq Sum() method. Here's our list with integer elements. List<int> list = new List<int> { 99, 34, 77, 75, 87, 35, 88}; Now find the sum using the Sum() method.

Can a Lambda statement return a value?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.


1 Answers

Test data

var ls=new List<OutputRow>();
ls.Add(new OutputRow(){propertyX=4});
ls.Add(new OutputRow(){propertyX=6});
ls.Add(new OutputRow(){propertyX=5});

Lambda

var total= ls.Sum(x=>x.propertyX);
like image 188
Arion Avatar answered Nov 10 '22 12:11

Arion