Samantha J T Star
Samantha J T Star

Reputation: 32798

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

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"?

Upvotes: 5

Views: 188

Answers (2)

neontapir
neontapir

Reputation: 4736

To build on what @J.Kommer said, the culture-sensitive check would look something like this:

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

Upvotes: 0

Johannes Kommer
Johannes Kommer

Reputation: 6451

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.

Upvotes: 8

Related Questions