优化Linq查询:按顺序排序

时间:2015-03-05 16:09:45

标签: c# linq

我有以下Linq查询,我发现LastRenewed调用我在哪里进行连接和订购需要花费将近一分钟。按顺序排序可将查询时间缩短30秒。有没有办法可以优化LastRenewed调用?

from stats in db.Stats 
group stats by stats.Id into st
join logs in db.Logs on st.Key equals logs.Id
select new
{
    //bunch of queries
    ... 
    LastRenewed = (from books in (db.Books.Where(x => x.BookId == st.Key))
                   join customer in db.Customers on books.Id equals customer.Id
                   orderby customer.LastRenewed descending
                   select customer.LastRenewed)
                  .FirstOrDefault(),
    ...
}

1 个答案:

答案 0 :(得分:-1)

db.Books.Where(x => x.BookId == st.Key)并将其存储在查询之外的某处,然后像这样使用它:

object books = `db.Books.Where(x => x.BookId == st.Key)`
LastRenewed = (from books in (books))
               join customer in db.Customers on books.Id equals customer.Id
               orderby customer.LastRenewed descending
               select customer.LastRenewed)
              .FirstOrDefault(),

这应该有所帮助。