-2

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!");
                }
            }

3 Answers3

3

Using FirstOrDefault method you can check whether object exist in your list or not, If exist it's first element of a sequence, else return default value in below example it's return null.

You can learn more about LINQ from here

public void Add(Car carToAdd)
{
        var qry = (from car in Cars
                   where car.Registration == carToAdd.Registration 
                   select car).FirstOrDefault();

        if(qry == null)
        {
           Cars.Add(carToAdd);
        }
        else 
        {
           Console.WriteLine("Reg already exists!");
        }
}
Jatin Parmar
  • 647
  • 4
  • 14
1
public void Add(Car carToAdd)
{
    if ( !Cars.Any(c => c.Registration == carToAdd.Registration) )
    {
        Cars.Add(carToAdd);
    }
    else 
    {
        // handle case where car is already in the list
    }
}
Rik
  • 28,507
  • 14
  • 48
  • 67
1

Most of answers suggest using Contains() method, I would suggest to use Any() as it's more flexible:

if ( !Cars.Any(c => c.Registration == carToAdd.Registration) )
    Cars.Add(carToAdd);

You can also use SingleOrDefault() to additionaly ensure that Your Cars' list is still satisfying this implicit requirement to have only a single car per registration:

var existing = Cars.SingleOrDefault(c => c.Registration == carToAdd.Registration) )

if(existing == null)
    Cars.Add(carToAdd);

SingleOrDefault() will throw if there are two or more elements satisfying the condition.

Community
  • 1
  • 1
Grzegorz Sławecki
  • 1,727
  • 14
  • 27