JSchwartz
JSchwartz

Reputation: 2724

How to sum a field grouped by another in LINQ?

I am trying to find a away to SUM all the QUANTITY for a specific RECIPE (all its ingredients) into a single value to get the TOTAL QUANTITY

Assuming I have the following dataset:

RecipeName IngredientName ReceiptWeight
Food1      Ingredient1    5
Food1      Ingredient2    2
Food2      Ingredient1    12
Food2      Ingredient3    1

And I would expect to get the following:

RecipeName ReceiptWeight
Food1      7
Food2      13

The code I have so far is:

            Grouping =
                (
                from data in dataset
                group data by data.RecipeName into recipeGroup
                let fullIngredientGroups = recipeGroup.GroupBy(x => x.IngredientName)
                select new ViewFullRecipe()
                {
                    RecipeName = recipeGroup.Key,
                    ReceiptWeight = ????

How can I get the value for RecipeWeight? Thanks,

Upvotes: 2

Views: 107

Answers (1)

Stephen Gilboy
Stephen Gilboy

Reputation: 5825

LINQ does have sum

from d in dataset
group d by new { d.RecipeName } into g
select new {
     g.Key.RecipeName,
     ReceiptWeight = g.sum(o => o.ReceiptWeight)
}

Upvotes: 3

Related Questions