Searching if value exists in a list of objects using Linq

后端 未结 9 1656
执念已碎
执念已碎 2020-12-04 05:17

Say I have a class Customer which has a property FirstName. Then I have a List.

Can LINQ be used to find if th

相关标签:
9条回答
  • 2020-12-04 05:42
    List<Customer> list = ...;
    Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");
    

    john will be null if no customer exists with a first name of "John".

    0 讨论(0)
  • 2020-12-04 05:46

    One option for the follow on question (how to find a customer who might have any number of first names):

    List<string> names = new List<string>{ "John", "Max", "Pete" };
    bool has = customers.Any(cus => names.Contains(cus.FirstName));
    

    or to retrieve the customer from csv of similar list

    string input = "John,Max,Pete";
    List<string> names = input.Split(',').ToList();
    customer = customers.FirstOrDefault(cus => names.Contains(cus.FirstName));
    
    0 讨论(0)
  • 2020-12-04 05:53

    LINQ defines an extension method that is perfect for solving this exact problem:

    using System.Linq;
    ...
        bool has = list.Any(cus => cus.FirstName == "John");
    

    make sure you reference System.Core.dll, that's where LINQ lives.

    0 讨论(0)
  • 2020-12-04 05:54

    Using Linq you have many possibilities, here one without using lambdas:

    //assuming list is a List<Customer> or something queryable...
    var hasJohn = (from customer in list
             where customer.FirstName == "John"
             select customer).Any();
    
    0 讨论(0)
  • 2020-12-04 05:54

    Try this, I hope it helps you.

     if (lstCustumers.Any(cus => cus.Firstname == "John"))
     {
         //TODO CODE
     }
    
    0 讨论(0)
  • 2020-12-04 05:56

    The technique i used before discovering .Any():

    var hasJohn = (from customer in list
          where customer.FirstName == "John"
          select customer).FirstOrDefault() != null;
    
    0 讨论(0)
提交回复
热议问题