开发者

Avoid repeating an expression in a LINQ to Entities query

I have the following query:

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 });
      }

Is it possible to avoid repeating the ((Bill)item).Payments.OrderByDescending(payment => payment.ID).Fir开发者_C百科stOrDefault() part 3 times? I tried turning it into a method and into a delegate - the code compiled in both cases, but produced an exception at runtime.


You can use the let contstruct as follows:

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

However, as you may noticed this uses the LINQ Query syntax vs. Method syntax. IIRC let is only available in the former.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜