How do I check if there is an entry in my collection that matches the criteria?

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

Is there an easy way to use Linq (or another) to find out if this collection has a book object called "Harry"?

+5
source share
2 answers

To do this, you can use the method Any():

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

This will go through your collection bookuntil you find a book called "Harry" or the end of your collection. If he finds a book with the correct title, it will stop passing through your collection and return true. If it reaches the end of your collection, it returns false.

: , . , .

+8

, ., :

book.Any(b => string.Compare(b.Title, "Harry", CultureInfo.CurrentCulture,
  CompareOptions.None) == 0);
0

All Articles