I am trying to implement an Add method which adds a car (object) to the fleet (list of objects)(i.e. adds the car to the list of cars).
The car to add should be a parameter of the method, and before adding a car to the list, I should perform check to see if the car exists in the list already using a LINQ statement to check if the registration already exist for any car in the existing list and if the car already exists in the list then I don’t add it.
Below is what I have done so far. If anyone can help, I would greatly appreciate it. Thanks.
public void Add(Car carToAdd)
{
var regQuery = Cars.Select(car => new { car.Registration });
foreach (var car in regQuery)
{
if (!regQuery.Contains(Car carToAdd.Registration))
{
Cars.Add(carToAdd);
}
else
{
Console.WriteLine("Reg already exists!");
}
}