简体   繁体   中英

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

I have a question about getting a list objects by "searching" their field names using LINQ. I've coded simple Library and Book classes for 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 Book instances which certain fields is equal to certain strings, like

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

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

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.

You could use FirstOrDefault Like this:

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

你的Book方法返回一本Book,我建议你返回一个列表,因为那个作者可能有不止一本书。

I would suggest using IndexOf instead of a simple equality to avoid casing problems.

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

Or if you only one the first book found in the list, use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM