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();
Your Book method returns a single Book, I would suggest returning a list as there could be more than one book with that author.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With