如何在LINQ中对另一个字段进行求和?

时间:2013-04-24 02:25:17

标签: c# linq

我正试图找到一个特定的RECIPE(所有成分)的所有QUANTITY到一个单一的值来获得总量的

假设我有以下数据集:

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

我希望得到以下内容:

RecipeName ReceiptWeight
Food1      7
Food2      13

我到目前为止的代码是:

            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 = ????

如何获取RecipeWeight的值? 谢谢,

1 个答案:

答案 0 :(得分:3)

LINQ确实有总和

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