C# Linq select/join with custom return type

Viewed 405

I have below linq sample:

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;
}

This mergeOrderAndFoodInformation function updates some fields of input foodOrderItem object and return updated foodOrderItem.

1- How can I write the select mergeOrderAndFoodInformation(foodOrderItem,orderItem) part in inline style if I don't want to use a function such mergeOrderAndFoodInformation to update and return result? I mean how can I change the select mergeOrderAndFoodInformation(foodOrderItem,orderItem) segment if I want to write the code without using an external function?

2- How can I write this linq query using Lambda notation?

P.S. Accept my apologies if keyword such as inline and external are not used correctly. I would be thankful if you correct me in case there are some mistakes.

2 Answers

You're modifying the objects in the source collection which is generally not a best practice when using Linq. It will require you to use lambda syntax to inline a function like so:

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()

Note that Join is uglier (IMHO) in lambda syntax and the inline function doesn't buy you a lot.

    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();

You can create the new object there itself.

Related