我正在学习OOP,同时做一些算法任务。我要把这个任务贴出来,因为有很多喜欢解决算法问题的"挑战家伙"。
我创建了一个"Car"类,它包含以下签名。它有发动机,货物和轮胎,这是单独的类。
汽车类别:
public Car(string model, Engine engine, Cargo cargo, List<Tire> tires)
{
this.Model = model;
this.Engine = engine;
this.Cargo = cargo;
this.Tire = tires;
}
public List<Tire> Tire { get; set; }
public Cargo Cargo { get; set; }
public Engine Engine { get; set; }
public string Model { get; set; }
货物等级:
public Cargo(int cargoWeight, string cargoType)
{
this.CargoWeight = cargoWeight;
this.CargoType = cargoType;
}
public string CargoType { get; set; }
public int CargoWeight { get; set; }
轮胎类别:
public Tire(double tirePreassure, int tireAge)
{
this.TireOneAge = tireAge;
this.TireOnePreassure = tirePreassure;
}
public double TireOnePreassure { get; set; }
public int TireOneAge { get; set; }
在货物类中,"cargoType"可以是"易碎品"或"易燃品"。tire类包含tireAge和tirepressure。我收到一个输入,看起来像这样:
2(汽车数量)
1。雪佛兰astro 200 180 1000易碎1.3 1 1.5 2 1.4 2 1.7 4
2。雪铁龙2cv 190 165 1200易碎0.9 3 0.85 2 0.95 2 1.1 1脆弱(cargoType)
我需要打印所有的汽车,他们的货物类型是易碎的,他们的tipressure低于1。
这是我的代码:
if (command == "fragile")
{
var newCars = cars
.Where(x => x.Cargo.CargoType == "fragile")
.Select(d => d
.Tire.Where(x => x.TireOnePreassure < 1.0))
.ToList();
}
但是这返回的是轮胎列表,而我需要的是带有特定信息的汽车列表。
完整代码:http://pastebin.com/wnfckfjV
任务:http://image.prntscr.com/image/8f04ee35b5be4a5d8c24e8cb91e69d02.png
if (command == "fragile")
{
var newCars = cars.Where(x =>
x.Cargo.CargoType == "fragile" &&
x.Tire.Any(tire => tire.TireOnePreassure < 1.0)
).ToList();
}
我认为以下内容应该能满足你的需求:
var newCars = cars.Where(c => c.Cargo.CargoType.Equals("fragile") &&
c.Tire.Any(t => t.TireOnePresssure < 1.0);
您可能需要检查Tire
是否为空