gpt4 book ai didi

c# - 如何在 LINQ 中对由另一个分组的字段求和?

转载 作者:行者123 更新时间:2023-11-30 22:18:17 27 4
gpt4 key购买 nike

我正在尝试找到一种方法,将特定食谱(其所有成分)的所有数量 SUM 为单个值以获得总数量

假设我有以下数据集:

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 的值?谢谢,

最佳答案

LINQ 确实有求和

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

关于c# - 如何在 LINQ 中对由另一个分组的字段求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16182355/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com