简体   繁体   中英

How to search a list of objects for a specific string attribute using LINQ in C#

I have the following code:

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

Before adding a new Car object to the Fleet list I need to check that 'registration' doesn't already exist as an attribute of any Car object in the list. This check needs to be using LINQ and inside the addToFleet method.

Assuming your Car class has a property Registration:

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

Simply check if there is Any car whose Registration matches with passed registration. If not Add .

public void addToFleet(String make, String model, String registration, int year, Double costPrice)
{
    if  (!Fleet.Any(x => x.Registration.ToLower() == registration.ToLower()))
        Fleet.Add(new Car(make, model, registration, year, costPrice));
}

I converted registration to lower so that string case do not become a problem. LINQ or Lambda expression. Dosen't matter. LINQ is converted to lambda by compiler.

First you should know how you can search with LINQ.

The SearchAdapter contains the core search functionality responsible for selecting data depending on the search criterion inputted by the user. There are three methods and one property in the class. The only part of the adapter available outside the class is the PerformSearch method, which is internal to the assembly.

Read this for its tutorial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM