Take List<Car>. Each Car has a unique index identifying it, say RegNumber and then another property describing it – say Color for example.
I want to
- check if the collection has a car with RegNumber 5
- if it does, change the color
- if it doesn’t, add a new item for that car
- save the list
This is the way I am currently doing it and I’m asking if there is a better, more efficient way of doing this?
Car car = CarsForSale.Find(c => c.RegNumber == 5);
if (car != null)
{
foreach (Car car in CarsForSale)
{
if (car.RegNumber == 5)
{
car.Color = "Red";
break;
}
}
}
else
{
CarsForSale.Add(new Car(5, "Red"));
}
Save(CarsForSale);
EDIT
There are not multiple cars with the same reg – the RegNumber is unique as stated in the question.
This was really just a total dumb@ss moment here anyway that a code review would have spotted. Thanks for all the replies and for not mocking my clearly stoopid question. Of course the item/element returned from the collection is a reference so there is absolutely no need to iterate through the list again…time to go bang my head against a wall I think.
Well first off you don’t need your test for
car.RegNumber == 5in the loop – you’ve already found the first car that match this criterion from your statement:In fact your whole loop is redundant, you can just have:
Unless you want to find all cars that have
RegNumberequal 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:With your original code the compiler should have warned you that the redefinition of
carin the loop would hide the original definition (the one I’ve quoted).