How to get/find an object by property value in a list

var myBooks = books.Where(book => book.author == "George R.R. Martin");

And remember to add: using System.Linq;

In your specific method, since you want to return only one book, you should write:

public Book GetBookByAuthor(string search)
{
    var book = books.Where(book => book.author == search).FirstOrDefault();
    // or simply:
    // var book = books.FirstOrDefault(book => book.author == search);
    return book;
}

The Where returns an IEnumerable<Book>, then the FirstOrDefault returns the first book found in the enumerable or null if no one has been found.

Leave a Comment