devfunkd
devfunkd

Reputation: 3234

LINQ Sum list of items grouped by type inside list

I have the following order object which contains a list of order addons. I am trying to create a report that shows all the addon types and their quantities summed.

public class Order {
     public IList<OrderAddon> OrderAddons { get; set; }
}

public class OrderAddon {
     public enum OrderType { get; set; }
     public string Name { get; set; }
     public int Quantity { get; set; }
}

This is where I am at and can't figure out if the entire query is wrong of I am just missing something.

var query = from order in Model.Orders
            from addon in order.OrderAddons
            group order by addon.AddonType
            into orderAddons select new
            {
                 Name = orderAddons.Key,
                 Quantity = orderAddons.Sum(x => x.) << This is where I am stuck
            };

When I hit . my intellisense is showing me properties in order object not the addon object.

Upvotes: 2

Views: 935

Answers (2)

Jose Ch.
Jose Ch.

Reputation: 3896

an alternative syntax same result...

var result = Model.Orders
  .SelectMany(order => order.OrderAddons)
  .GroupBy(addon => addon.OrderType)
  .Select(grouping => new
  {
      Name = grouping.Key,
      Quantity = grouping.Sum(addon => addon.Quantity)
  });

Upvotes: 4

StriplingWarrior
StriplingWarrior

Reputation: 156544

That's because you're saying group order by ..., so the orderAddons object becomes a grouping of orders. You can use this if you're going to need properties from both objects:

from order in Model.Orders
from addon in order.OrderAddons
group new{addon, order} by addon.AddonType
into orderAddons select new
{
    Name = orderAddons.Key,
    Quantity = orderAddons.Sum(x => x.addon.Quantity)
};

If this is all the data you need, this is a little simpler:

from order in Model.Orders
from addon in order.OrderAddons
group order.Quantity by addon.AddonType
into quantityByAddonType select new
{
    Name = quantityByAddonType.Key,
    Quantity = quantityByAddonType.Sum()
};

Upvotes: 4

Related Questions