【发布时间】:2019-10-17 06:19:54
【问题描述】:
我想问,在List 或Array 中找到某个对象列表的参数的最大值是否有一个简短的形式。
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 => car.power)。
【问题讨论】: