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

I had a question about how to get list objects by searching for their field names using LINQ. I encoded simple classes Libraryand Bookfor this:

class Book
{
    public string title { get; private set; }
    public string author { get; private set; }
    public DateTime indexdate { get; private set; }
    public int page { get; private set; }

    public Book(string title,string author, int page)
    {
        this.title = title;
        this.author = author;
        this.page = page;
        this.indexdate = DateTime.Now;
    }
}

class Library
{
    List<Book> books = new List<Book>();

    public void Add(Book book)
    {
        books.Add(book);
    }

    public Book GetBookByAuthor(string search)
    {
        // What to do over here?
    }
}

So, I want to get instances Bookfor which certain fields are equal to certain rows, for example

if(Book[i].Author == "George R.R. Martin") return Book[i];

I know this is possible with simple loop codes, but I want to do it with LINQ. Is there any way to achieve this?

+4
source share
4 answers
var myBooks = books.Where(book => book.author == "George R.R. Martin");

And don't forget 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;
}

Where IEnumerable<Book>, FirstOrDefault , null, .

+6

FirstOrDefault :

public Book GetBookByAuthor(string search)
{
    return books.FirstOrDefault(c => c.author == search);
}
+2
var books = books.Where(x => x.author == search).ToList();

Book , , .

0

IndexOf , .

var myBooks = books.Where(x => x.author.IndexOf("George R.R. Martin", StringComparison.InvariantCultureIgnoreCase) >= 0);

, , ,

var myBook = books.FirstOrDefault(x => x.author.IndexOf("George R.R. Martin", StringComparison.InvariantCultureIgnoreCase) >= 0);
0

All Articles