0
我有以下查詢:避免重複的表達式在一個LINQ實體查詢
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次?我嘗試將它轉換爲一個方法並轉化爲委託 - 兩種情況下編譯的代碼,但是在運行時產生了一個異常。
謝謝!在http://www.pluralsight-training.net/community/blogs/keith/archive/2009/10/07/using-let-in-linq-with-extension-method-syntax.aspx的幫助下,我設法使用方法語法重寫它:'val = val.Select(bill => new {Bill = bill,LastPayment =((Bill)item).Payments.OrderByDescending(payment => payment.ID).FirstOrDefault()}) .Select(item => new SimpleBill { LastPaymentDate = item.LastPayment.CTime, //其餘字段 });' – SlimShaggy