【问题标题】:Maximum of a Object-Parameter in an Object-List [duplicate]对象列表中对象参数的最大值
【发布时间】:2019-10-17 06:19:54
【问题描述】:

我想问,在ListArray 中找到某个对象列表的参数的最大值是否有一个简短的形式。

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Car car1 = new Car(120);
        Car car2 = new Car(140);
        Car car3 = new Car(100);
        List<Car> cars = new List<Car> { car1, car2, car3 };

        // THIS I WANT TO SHORTEN ██████████
        // ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
        // Find car with maximum Power
        double max = 0;
        foreach (Car car in cars)
            if (car.power > max)
                max = car.power;
        // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
        // █████████████████████████████████

        Console.WriteLine("The maximum power is = " + max);
    }

    public class Car
    {
        public double power; // Horsepower of the car
        public Car (double power)
        {
            this.power = power;
        }
    }
}

我正在寻找一些简单的东西,比如cars.findMax(car =&gt; car.power)

【问题讨论】:

    标签: c# list class


    【解决方案1】:

    您可以为此使用 LINQ:

    var max = cars
        .Select(c => c.power)
        .DefaultIfEmpty(0)
        .Max();
    
    • .Select(c =&gt; c.power) 将从每个对象中选择 power 属性。
    • 如果cars 中没有任何内容,.Max() 将抛出InvalidOperationException 错误,因此我们将默认设置为0.DefaultIfEmpty(0)
    • .Max() 听起来像,将返回最大值。

    如果您绝对 100% 确定 cars 永远不会为空,那么您也可以跳过所有这些并执行以下操作:

    var max = cars.Max(c => c.power);
    

    【讨论】:

    • 不错!如果我采用类似getPower() 的方法而不是像power 这样的参数,也可以工作。非常感谢!
    【解决方案2】:

    您可以为此使用 LINQ

     var max = cars.Max(i => i.power);
    

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2017-01-25
      相关资源
      最近更新 更多