2011-08-06 47 views
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次?我尝试将它转换为一个方法并转化为委托 - 两种情况下编译的代码,但是在运行时产生了一个异常。

回答

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只适用于前者。

+0

谢谢!在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