[英]Get maximum value in a list within a list in LINQ
Here's my code:这是我的代码:
public class Calculation
{
public int Id;
public string ErrorCode;
public ICollection<CalculationDetails> CalculationDetails;
}
public class CalculationDetails
{
public int Id;
public decimal? Amount;
public decimal? Rate;
public string Category;
}
public static Category
{
public const string CategoryA = "A";
public const string CategoryB = "B";
}
I am having a list of calculations in the object List<Calculation> calculations
.我在 object List<Calculation> calculations
中有一个计算列表。
I want to fetch the maximum of Amounts of Category B from Calculations object.我想从计算 object 中获取 B 类的最大数量。
List<Calculation> calculations = ...
Decimal max = calculations
.Where( c => c != null )
.SelectMany( c => c.CalculationDetails )
.Where( cd => cd != null )
.Where( cd => cd.Category == Category.CategoryB )
.Select( cd => cd.Amount ?? 0 )
.DefaultIfEmpty( 0 )
.Max();
Feel free to elide the .Where( x => x != null )
if you're confident there are no nulls.如果您确信没有空值,请.Where( x => x != null )
。
Try this:尝试这个:
var calculations = new List<Calculation>(); //pretend it's filled
var maxAmountCategoryB = calculations
.SelectMany(c => c.CalculationDetails)
.Where(d => d.Category == Category.CategoryB)
.Max(d => d.Amount.GetValueOrDefault());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.