Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally get the sum from a list

Tags:

c#

list

linq

I have a class PropertyDetails:

public class PropertyDetails 
{      
    public int Sequence { get; set; } 

    public int Length { get; set; }   

    public string Type { get; set; } 
} 

I am creating a list of PropertyDetails as

List<PropertyDetails> propertyDetailsList = new List<PropertyDetails>();

I want the sum of Length from the list where PropertyDetails.Sequence < sumValue=4

Linq solutions are welcome.

like image 206
PramodChoudhari Avatar asked Nov 28 '22 06:11

PramodChoudhari


2 Answers

Sum of the Lengths where the Sequence is less than 4:

 var result = propertyDetailsList.Where(d => d.Sequence < 4)
                                 .Sum(d => d.Length);
like image 148
dtb Avatar answered Dec 14 '22 23:12

dtb


You can use the Sum extension method from linq. First you filter out those items that don't fulfill your condition using Where. Then you either use Select(pd=>pd.Length).Sum(), or the overload that maps the item from PropertyDetail to Length using the function passed to Sum().

const int sumValue = 4;
propertyDetailsList
    .Where(pd=>pd.Sequence < sumValue)
    .Sum(pd=>pd.Length);
like image 39
CodesInChaos Avatar answered Dec 14 '22 22:12

CodesInChaos