[英]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.