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