Conditionally get the amount from the list

I have a PropertyDetails class:

public class PropertyDetails { public int Sequence { get; set; } public int Length { get; set; } public string Type { get; set; } } 

I create a list of PropertyDetails as

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

I want to get the Length sum from the list, where PropertyDetails.Sequence <sumValue = 4

Linq solution is welcome.

+4
source share
4 answers

Sum of lengths where the sequence is less than 4:

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

You can use Sum extension method from linq. First, you filter out those elements that do not match your state using Where . Then you use either Select(pd=>pd.Length).Sum() , or an overload that displays the element from the PropertyDetail to Length using the function passed to Sum() .

 const int sumValue = 4; propertyDetailsList .Where(pd=>pd.Sequence < sumValue) .Sum(pd=>pd.Length); 
+7
source
 int sumLength = propertyDetailsList.Where(p => p.Sequence < 4).Sum(p => p.Length); 
+6
source
 var list = from p in propertyDetailsList where p.Sequence < 4 select p.Length; Console.WriteLine("sum is {0}", list .Sum()) 
+3
source

Source: https://habr.com/ru/post/1335986/


All Articles