通过将值存储在select中来优化linq查询

时间:2019-03-04 16:05:45

标签: c# entity-framework linq

我对linq查询有疑问。在“选择”中,我两次获得同一项目,这使得代码执行时间超出了我的承受能力。有什么方法可以在x.OrderByDescending(z => z.Date).FirstOrDefault()查询中存储Select项?

执行时间:180毫秒

var groups = dataContext.History
    .GroupBy(a => new { a.BankName, a.AccountNo })
    .Select(x => new HistoryReportItem
    {
        AccountNo = x.FirstOrDefault().AccountNo,
        BankName = x.FirstOrDefault().BankName,
        IsActive = x.FirstOrDefault().IncludeInCheck,
    })
    .ToList();

执行时间:1200毫秒

var groups = dataContext.History
    .GroupBy(a => new { a.BankName, a.AccountNo })
    .Select(x => new HistoryReportItem
    {
        AccountNo = x.FirstOrDefault().AccountNo,
        BankName = x.FirstOrDefault().BankName,
        IsActive = x.FirstOrDefault().IncludeInCheck,
        LastDate = x.OrderByDescending(z => z.Date).FirstOrDefault().Date,
    })
    .ToList();

执行时间:2400毫秒

var groups = dataContext.History
    .GroupBy(a => new { a.BankName, a.AccountNo })
    .Select(x => new HistoryReportItem
    {
        AccountNo = x.FirstOrDefault().AccountNo,
        BankName = x.FirstOrDefault().BankName,
        IsActive = x.FirstOrDefault().IncludeInCheck,
        LastDate = x.OrderByDescending(z => z.Date).FirstOrDefault().Date,
        DataItemsCount = x.OrderByDescending(z => z.Date).FirstOrDefault().CountItemsSend
    })
    .ToList();

1 个答案:

答案 0 :(得分:0)

您可以尝试通过两个步骤进行选择:

var groups = dataContext.History
    .GroupBy(a => new { a.BankName, a.AccountNo })
    .Select(x => new 
    {
        first = x.FirstOrDefault();
        lastDate = x.OrderByDescending(z => z.Date).FirstOrDefault();
    }
    .Select(x => new HistoryReportItem
    {
        AccountNo = x.first.AccountNo,
        BankName = x.first.BankName,
        IsActive = x.first.IncludeInCheck,
        LastDate = x.lastDate.Date,
        DataItemsCount = x.lastDate.CountItemsSend
    })
    .ToList();

如果失败,则可能是因为引擎无法将其完全转换为SQL,您可以尝试在两个AsEnumerable()之间添加Select