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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With