Well first off you don't need your test for car.RegNumber == 5
in the loop - you've already found the first car that match this criterion from your statement:
Car car = CarsForSale.Find(c => c.RegNumber == 5);
In fact your whole loop is redundant, you can just have:
if (car != null)
{
car.Color = "Red";
}
else
{
CarsForSale.Add(new Car(5, "Red"));
}
Unless you want to find all cars that have RegNumber
equal to 5, in which case your first line is incorrect as that will only find the first car that matches the criteria. To find all the cars you want something along these lines:
var cars = CarsForSale.Where(c => c.RegNumber == 5);
foreach (Car car in cars)
{
car.Color = "Red";
}
if (!car.Any())
{
CarsForSale.Add(new Car(5, "Red"));
}
With your original code the compiler should have warned you that the redefinition of car
in the loop would hide the original definition (the one I've quoted).