C# – Searching if value exists in a list of objects using Linq

clinq

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

Can LINQ be used to find if the list has a customer with Firstname = 'John' in a single statement.. how?

Best Answer

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.