Coder Perfect

Linq is used to check if a value exists in a list of objects.

Problem

Let’s say I have a Customer class with a property called FirstName. Following that, I have a ListCustomer>.

In a single query, can LINQ be used to find if the list has a client with Firstname = ‘John’?

Asked by Tony_Henrich

Solution #1

LINQ has an extension technique that is ideal for dealing with this problem:

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

Make certain to cite System. LINQ can be found in Core.dll.

Answered by Andriy Volkov

Solution #2

zvolkov’s response is ideal for determining whether such a customer exists. If you need to use the customer again later, you can perform the following:

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

I realize this isn’t the question you’re asking, but I though I’d ask ahead of time to avoid a follow-up:) (Of course, this just finds the first such customer; if you want to locate all of them, simply use a regular where clause.)

Answered by Jon Skeet

Solution #3

One possibility for the follow-up inquiry (how to locate a customer with a variety of first names):

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

how to obtain a client from a csv file with a similar list

string input = "John,Max,Pete";
List<string> names = input.Split(',').ToList();
customer = customers.FirstOrDefault(cus => names.Contains(cus.FirstName));

Answered by Mike Sackton

Solution #4

There are numerous choices when using Linq, including one that does not require the use of lambdas:

//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
         where customer.FirstName == "John"
         select customer).Any();

Answered by jmservera

Solution #5

customerList.Any(x=>x.Firstname == "John")

Answered by Chris Brandsma

Post is based on https://stackoverflow.com/questions/1071032/searching-if-value-exists-in-a-list-of-objects-using-linq