I have a list of Books, each book has a linked Author. My Api allows a user to search either by Title or Author.
In the Api i have a search Model
public class SearchOptions
{
public string Title { get; set; }
public string Author { get; set; }
}
The user may use both fields or just Title or just Author.
Here are my my Books and Author Models
public class Book
{
public string Title { get; set; }
public string Description { get; set; }
public Author LinkedAuthor { get; set; }
}
public class AuthorEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
I've created the following Linq query but its not quite right because when the author is not completed i.e. it's a blank string i get all the results back.
I almost want to say if the string is not null or empty then apply the filter for author (and the same with the title) but I'm not sure how to do this in Linq?
var returnedBooks = _bookRepository.GetAll()
.Where(x => x.Title.Contains(title) ||
(x.LinkedAuthor.FirstName + " " + x.LinkedAuthor.LastName).Contains(authorName)).ToList();