Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 634
Doğa Can Kılıç Avatar asked Mar 15 '16 15:03

Doğa Can Kılıç


3 Answers

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.

like image 115
Tommaso Bertoni Avatar answered Oct 31 '22 21:10

Tommaso Bertoni


You could use FirstOrDefault Like this:

public Book GetBookByAuthor(string search)
{
    return books.FirstOrDefault(c => c.author == search);
}
like image 4
Salah Akbari Avatar answered Oct 31 '22 21:10

Salah Akbari


var books = books.Where(x => x.author == search).ToList();

Your Book method returns a single Book, I would suggest returning a list as there could be more than one book with that author.

like image 2
James Dev Avatar answered Oct 31 '22 21:10

James Dev