我有以下代码:
private List<Car> Fleet = new List<Car>()
{
new Car("Toyota", "Corola","YI348J", 2007, 7382.33),
new Car("Renault", "Megane","ZIEKJ", 2001, 1738.30),
new Car("Fiat", "Punto","IUE748", 2004, 3829.33)
};
public void addToFleet(String make, String model, String registration, int year, Double costPrice)
{
Fleet.Add(new Car(make, model, registration, year, costPrice));
}
在将新的 Car 对象添加到 Fleet 列表之前,我需要检查“注册”是否已作为列表中任何 Car 对象的属性存在。此检查需要使用 LINQ 并在 addToFleet 方法中进行。
最佳答案
假设您的 Car 类有一个属性注册:
private List<Car> Fleet = new List<Car>()
{
new Car("Toyota", "Corola","YI348J", 2007, 7382.33),
new Car("Renault", "Megane","ZIEKJ", 2001, 1738.30),
new Car("Fiat", "Punto","IUE748", 2004, 3829.33)
};
public void addToFleet(String make, String model, String registration, int year, Double costPrice)
{
if(Fleet.Any(car => car.Registration == registration))
{
// already in there
}
else
{
Fleet.Add(new Car(make, model, registration, year, costPrice));
}
}
关于c# - 如何在 C# 中使用 LINQ 搜索特定字符串属性的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395839/