GlobalJim
GlobalJim

Reputation: 1209

Combine the values of a certain property based on the value of a different property in a List of Objects in C#?

Currently I have a List<OrderModel>. OrderModel is a class that contains two properties: OrderId and Total. In this case OrderId is NOT unique. I want to combine the values of the Total property where OrderId matches.

I have a solution, but I want to know if there is a better way (speaking in terms of performance) of accomplishing this task. Here is what I am currently doing:

As I fill my List<OrderModel> object I also add the OrderId to a List<long>. So now that I have two lists.

foreach (var id in orderIdList.Distinct())
{
    var orders = orderModelList.Where(l => l.OrderId == id).ToList();
    if (orders.Count() > 1)
    {
        var firstOrder = orders.FirstOrDefault();
        orders.Remove(firstOrder);
        foreach (var order in orders)
        {
        firstOrder.Total += order.Total;
        orderModelList.Remove(order);                    
        }
     }
}

Upvotes: 2

Views: 57

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39037

You're doing a lot of useless enumerations in your version. Assuming you have a list of orders, you can use GroupBy to do most of the filtering:

var orderModelList = orders.GroupBy(o => o.Id)
    .Select(group => new OrderModel
    {
        Id = group.Key,
        Total = group.Sum(o => o.Total)
    })
    .ToList();

Upvotes: 4

Related Questions