避免在LINQ to Entities查询中重复表达式

时间:2011-08-06 10:27:14

标签: optimization linq-to-entities

我有以下查询:

val = val.Select(item => new SimpleBill { CTime = item.CTime, Description = item.Description, ID = item.ID,
      IDAccount = item.IDAccount, OrderNumber = item.OrderNumber, PSM = item.PSM, Sum = item.Sum,
      Type = (BillType)item.Type,
      ByteStatus = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().Status,
      LastPaymentDate = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().CTime,
      LastPaymentSum = ((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault().Sum });
      }

是否可以避免重复((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault()部分3次?我尝试将其转换为方法并转换为委托 - 在两种情况下编译的代码,但在运行时产生异常。

1 个答案:

答案 0 :(得分:1)

您可以按如下方式使用let contstruct:

val = from item in val
let lastPayment = ((Bill)item).Payments
   .OrderByDescending(payment => payment.ID)
   .FirstOrDefault()
select new SimpleBill
{
    lastPayment.CTime,
    //Rest of fields
}

但是,您可能已经注意到这使用了LINQ查询语法与方法语法。 IIRC let仅适用于前者。