![](/img/trans.png)
[英]Get the objects with the maximum value for a specific property from a list using LINQ
[英]Get maximum value in a list within a list in LINQ
这是我的代码:
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";
}
我在 object List<Calculation> calculations
中有一个计算列表。
我想从计算 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();
如果您确信没有空值,请.Where( x => x != null )
。
尝试这个:
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());
你可以使用
var result = listOfCalculation.Max(x=>x.CalculationDetails
.Where(c=>c.Category.Equals(Category.CategoryB))
.Max(c=>c.Amount));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.