c# - LINQ Min() 和 Max() 优化

标签 c# linq

我在做对时遇到了一些麻烦。

我需要为列表中的列表中的列表选择最小值和最大值

有没有想过如何创建优化的类型?

var range = allFilteredCars
            .SelectMany(car => car.LeasingPlans
                .SelectMany(plan => plan.Durations)
                .Select(a => a.MonthlyPrice))
            .ToList();

        var min = range.Min();
        var max = range.Max();

最后的Min()Max()感觉不太对。

有什么想法吗?

最佳答案

我只能想到一种方法来计算 minmax 只需在整个集合上迭代一次,这可以使用 foreach 循环

var min = Int32.MaxValue;
var max = Int32.MinValue;
foreach(var filteredCard in allFilteredCars)
{
    foreach(var leasingPlan in filteredCard.LeasingPlans) 
    {
        foreach(var car in leasingPlan.Durations) 
        {
          if(car.MonthlyPrice < min)
            min = car.MonthlyPrice;
          else if(car.MonthlyPrice > max)
            max = car.MonthlyPrice;
        }
     }
}

Assuming MonthlyPrice is of Int

关于c# - LINQ Min() 和 Max() 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50619744/

相关文章:

c# - 如何围绕数据库中的空值设计类?

c# - Selenium native android 应用程序的 DesiredCapabilities 已过时

c# - 两个流的条件配对 - 在响应式扩展中组合 If

asp.net - 比较2个linq应用程序: Unexpected result

c# - 在 EF 查询中添加 DateTime 和 TimeSpan 的代码示例

c# - Linq C# 基于变量的查询

c# - Javascript onKeyPress 事件不起作用?

c# - 我们可以在 mvvm 中应用存储过程吗?有道理的解释

c# - Expression.Body.Expressions——如何使用它?

c# - ASP.Net 核心 : Get User Roles with LinQ Select method