Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if there's a record in my collection that matches a criteria?

Tags:

c#

linq

I have a collection of Book objects called book. The Book class has a field called Title.

Is there an easy way using Linq (or other) to find out if that collection has a Book object with a title of "Harry"?

like image 453
Samantha J T Star Avatar asked Nov 22 '11 16:11

Samantha J T Star


1 Answers

You can use the Any() method for this:

book.Any(b => string.Equals(b.Title, "Harry"));

This will go through your book collection until it finds a book with the Title "Harry" or the end of your collection. If it finds a book with the correct title it stops going through your collection and returns true. If it reaches the end of your collection it returns false.

Edit: Please note, this does a culture-insensitive equality check. You might want to do a culture-sensitive one instead depending on your use-case.

like image 85
Johannes Kommer Avatar answered Nov 16 '22 17:11

Johannes Kommer