我有以下代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
在将新的Car对象添加到Fleet列表之前,我需要检查"registration"是否已经作为列表中任何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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
509 次 |
| 最近记录: |