298

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?

10 Answers 10

578

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Any is good, I wonder how many developers use Count when they should use Any?
You can also do a case insensitive search: cus => cus.FirstName.Equals("John", StringComparison.CurrentCultureIgnoreCase)
I know this is an old question but why aren't we making use of the Exists method? Seeing as it is made to see if things exist.
Because not all collections have Exists, and it does not take a lambda expression, but rather the object we are looking for itself.
@zvolkov, Any ideas why my resharper is suggesting I use bool has = list.All(cus => cus.FirstName != "John"); Is this more optimal ?
126

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.)

4 Comments

I'd point out that you might appreciate having done this later when it comes to debugging, if you find yourself suddenly curious which customer it was that fit the criteria.
Just bumping this answer up one cos I love the way SO community goes the extra step to add even more to the question/answer.
thanks it helped me, but sometimes i just want to get bool result , so in that case .Any or .FindIndex is used here which is fast ?
@stom: They're both O(N), basically... they're just linear searches.
30

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

Comments

10

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

Comments

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

4 Comments

This does not answer the question "if" such an entry exists; it merely enumerates the values if they do exist. An extra step is needed to determine if this enumeration is nonempty.
Then change the Where to Any. Probably more philosophical for me. I rarely need to know if without caring which ones they are. @jmservera: you were right. I gave up LINQ a while back and now use Lambda exclusively.
I don't mean to be pedantic when I say that using the lambda calls is still technically using LINQ. (In particular, you're using LINQ-to-Objects.) You're just using the method calls rather than language keywords.
How does this answer differ from the zvolkov's?
4

The technique i used before discovering .Any():

var hasJohn = (from customer in list
      where customer.FirstName == "John"
      select customer).FirstOrDefault() != null;

Comments

3
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".

3 Comments

That will throw an exception if more than one customer is called John.
Thanks for the comment. I'll leave the answer as a partially correct example.
It's still valid in a scenario when you are sure there is 1 and you want an exception to be raised if more than one, so I think it is good that you didn't delete it.
3

Try this, I hope it helps you.

 if (lstCustumers.Any(cus => cus.Firstname == "John"))
 {
     //TODO CODE
 }

1 Comment

That's the same as the accepted answer from over 8 years ago. Please make sure your answer is unique among all the answers.
1

Another possibility

if (list.Count(customer => customer.Firstname == "John") > 0) {
 //bla
}

1 Comment

Its' preferable to use Any in this scenario.
0

Include using System.Linq

Use Trim() if there should be a match even with leading and trailing whitespaces.

Use StringComparison.CurrentCultureIgnoreCase if the match needs to
be case insensitive.

using System.Linq;
...
    bool has = list.Any(cus => cus.FirstName.Trim().Equals("John", StringComparison.CurrentCultureIgnoreCase));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.