简体   繁体   English

在 LINQ 中的列表中获取列表中的最大值

[英]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());

You could use你可以使用

var result = listOfCalculation.Max(x=>x.CalculationDetails
                                  .Where(c=>c.Category.Equals(Category.CategoryB))
                                  .Max(c=>c.Amount));

Demo Code演示代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM