开发者

Conditionally get the sum from a list

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.


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

 var result = propertyDetailsList.Where(d => d.Sequence < 4)
                                 .Sum(d => d.Length);


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);


int sumLength = propertyDetailsList.Where(p => p.Sequence < 4).Sum(p => p.Length);


var list = from p in propertyDetailsList
   where p.Sequence < 4
   select p.Length;

Console.WriteLine("sum is {0}", list .Sum())


decimal? dRemainingBalance = dataModal.Where(x => x.StatusID == 100 || x.StatusID == 200 || x.StatusID == 300).Sum(x => Convert.ToDecimal(x.RemainingBalance));

Conditionally get the sum from a list

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜