Question

is it possible to have a better optimisation of this linq query:

var query = Context.books.Where(book=> book.Author == "Murakami"
                                        && book.Year = 2004
                                        && book.price ==
                                        Context.books.Where(book => book.Author == Murakami")
                                        .Max(c => c.price));

I'm interested in the Max part because Author is the same as a little bit above

Was it helpful?

Solution

if you want the most Expensive book from Murakami in 2004

This will retrieve 0 or 1 book.

var mostExpensiveBook = Context.books.Where(book => book.Author = "Murakami" &&
                                        book.Year == 2004)
                         .OrderByDescending(m => m.price)
                         .FirstOrDefault();

if you want all the books from Murakami 2004 which have a price equivalent to the most expensive Murakami's book, you may rewrite your query to (equivalent to your query, just avoiding repeating "Murakami" and using a let keyword).

this will retrieve 0-n book(s).

var books = context.Books.Where(m => m.Author == "Murakami");

var mostExpensiveBooks = from book in books 
                         let mostExpensivePrice = books.Max(x => x.price)
                         where book.price == mostExpensivePrice &&
                               book.Year == 2004
                         select book;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top