Linq使用select new来计算另一个字段

时间:2017-05-11 15:31:45

标签: linq

是否可以在linq中执行以下操作:select new我在TotalOrderItems中使用TotalInStockItems中的值作为var Order = (from o in orderItems select new ShippingOrder { OrderId = orderItems.OrderId TotalOrderItems = orderItems.GroupBy(x => x.Sku).Count(), TotalInStockItems = TotalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(), }).ToList(); 计算的一部分?

{{1}}

1 个答案:

答案 0 :(得分:2)

尝试使用let clause (C# Reference)存储该值,以便稍后在查询中使用

(from o in orderItems
 let totalOrderItems = orderItems.GroupBy(x => x.Sku).Count()
 select new ShippingOrder { 
     OrderId = o.OrderId
     TotalOrderItems = totalOrderItems,
     TotalInStockItems = totalOrderItems - orderItems.Where(x => x.InStock =='F').GroupBy(x => x.Sku).Count(),
 }).ToList();