Searching if value exists in a list of objects using Linq

后端 未结 9 1657
执念已碎
执念已碎 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:57

    zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:

    Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
    if (customer != null)
    {
        // Use customer
    }
    

    I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where clause.)

    0 讨论(0)
  • 2020-12-04 06:01
    customerList.Any(x=>x.Firstname == "John")
    
    0 讨论(0)
  • 2020-12-04 06:04

    Another possibility

    if (list.Count(customer => customer.Firstname == "John") > 0) {
     //bla
    }
    
    0 讨论(0)
提交回复
热议问题