如何在 C# 中使用 LINQ 搜索特定字符串属性的对象列表

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

我有以下代码:

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

在将新的 Car 对象添加到 Fleet 列表之前,我需要检查 'registration' 是否已作为列表中任何 Car 对象的属性存在。此检查需要使用 LINQ 并在 addToFleet 方法中进行。

首先您应该了解如何使用 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 这是它的教程。

只需检查是否有 Any 辆车的注册与通过的注册匹配。如果不是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));
}

我将注册转换为小写,这样字符串大小写就不会成为问题。 LINQ 或 Lambda 表达式。没关系。 LINQ 被编译器转换为 lambda。

假设您的汽车 class 有 属性 登记:

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