我有以下linq示例:
List<FoodOrderItem> foodOrderItems = foodItemsWithPricesDbResult.ResultValue;
List<FoodOrderItem> orderItemsWithDiscounts= (from orderItem in order.Items
join foodOrderItem in foodOrderItems
on orderItem.FoodId equals foodOrderItem.Id
select mergeOrderAndFoodInformation(foodOrderItem,orderItem)).ToList();
.
.
.
private static FoodOrderItem mergeOrderAndFoodInformation(FoodOrderItem foodOrderItem, OrderItem orderItem)
{
foodOrderItem.DiscountValue = orderItem.DiscountValue;
foodOrderItem.DiscountKind = orderItem.DiscountKind;
foodOrderItem.CurrentOrderedCount = orderItem.Count;
return foodOrderItem;
}
此mergeOrderAndFoodInformation
函数更新输入foodOrderItem
对象的某些字段并返回更新的foodOrderItem。
1-如果我不想使用诸如select mergeOrderAndFoodInformation(foodOrderItem,orderItem)
之类的函数来更新和返回结果,该如何以 inline 风格编写mergeOrderAndFoodInformation
部分?我的意思是,如果我想在不使用外部函数的情况下编写代码,该如何更改select mergeOrderAndFoodInformation(foodOrderItem,orderItem)
段?
2-如何使用Lambda表示法编写此linq查询?
P.S。如果没有正确使用inline
和external
之类的关键字,请接受我的歉意。如果有一些错误,请您纠正我,我将不胜感激。
答案 0 :(得分:1)
您正在修改源集合中的对象,这在使用Linq时通常不是最佳实践。它将要求您使用lambda语法内联如下函数:
order.Items.Join(foodOrderItems, oi=>oi.FoodId, foi=>foi.Id, (oi, foi) => new {oi, foi})
.Select(j => {
j.foi.DiscountValue = j.oi.DiscountValue;
j.foi.DiscountKind = j.oi.DiscountKind;
j.foi.CurrentOrderedCount = j.oi.Count;
return j.foi;
})
.ToList()
请注意,Join
在lambda语法中较丑(IMHO),并且内联函数不会给您带来很多好处。
答案 1 :(得分:0)
List<FoodOrderItem> foodOrderItems = foodItemsWithPricesDbResult.ResultValue;
List<FoodOrderItem> orderItemsWithDiscounts = (from orderItem in order.Items
join foodOrderItem in foodOrderItems
on orderItem.FoodId equals foodOrderItem.Id
select new FoodOrderItem
{
DiscountValue = orderItem.DiscountValue,
DiscountKind = orderItem.DiscountKind,
CurrentOrderedCount = orderItem.Count
}).ToList();
您可以在那里自己创建新对象。