【问题标题】:Group by Sum for Calculated field in LinqLinq中计算字段的总和分组
【发布时间】:2018-03-24 00:47:56
【问题描述】:

我想为表之间的三向连接创建一个计算字段。这三个表被命名为Recipes、Ingredients 和IngredientsToRecipes。这些表携带的值如下:

食谱

  • recipeID
  • 用户ID
  • 姓名
  • 说明

成分

  • 姓名
  • 价格
  • 说明

配料到食谱

  • recipeID

现在,我开始进行三向连接,然后按配方分组,因为连接中会有很多重复项,我是这样做的:

var recipesJoin = (
    from a in db.IngredientsToRecipes
    join b in db.Recipes on a.recipeID equals b.recipeID
    join c in db.Ingredients on a.siin equals c.siin
    select new
    {
        recipeID = a.recipeID,
        userID = b.userID,
        name = b.name,
        description = b.description,
        price = c.price
    }).GroupBy(x=>x.recipeID);

我的计划是然后从 recipesJoin 创建一个新表,我将汇总价格,然后只返回价格低于变量 y 的行。我已经尝试了很多东西,但我对 Linq 的理解是从今天开始的,所以我受到了严重的限制。 我试过了

var recipesJoin = (
    from a in db.IngredientsToRecipes
    join b in db.Recipes on a.recipeID equals b.recipeID
    join c in db.Ingredients on a.siin equals c.siin
    select new
    {
        recipeID = a.recipeID,
        userID = b.userID,
        name = b.name,
        description = b.description,
        price = c.price
    }).GroupBy(x=>x.recipeID).Sum(y=>y.price);

但我得到了错误:

严重性代码描述项目文件行抑制状态 错误 CS1061 'IGrouping>' 不包含'price' 的定义,并且找不到接受'IGrouping>' 类型的第一个参数的扩展方法'price'(您是否缺少 using 指令或程序集引用?) SalWebAPI C :\Users\Samuel.endeva\source\repos\SalApp\SalApp\SalWebAPI\Controllers\RecipeTypeBudgetController.cs 31 活动

我不太明白这个错误。我的主要目标是汇总并分组到一个计算字段中,删除高于某个价格的行,然后将该新表与另一个表连接以进行简单检查。我该如何计算这样的 3 路连接的总和?

【问题讨论】:

  • “我不太明白这个错误。” 应用 GroupBy 后,您将获得组,但他们没有价格。该组知道它的密钥和项目。

标签: c# postgresql entity-framework linq


【解决方案1】:

您应该选择分组操作后的结果。由于您是按 recipeID 分组的,因此我相信您想要每个唯一食谱 ID 的总价,因此建议如下:

var recipesJoin = (
      from a in db.IngredientsToRecipes
      join b in db.Recipes on a.recipeID equals b.recipeID
      join c in db.Ingredients on a.siin equals c.siin
      select new
      {
          recipeID = a.recipeID,
          userID = b.userID,
          name = b.name,
          description = b.description,
          price = c.price
      }).GroupBy(x => x.recipeID) // 1
          .Select(grp=> new //2
          {
              recipeID = grp.Key,
              name= grp.First().name, // same ID => same name anyway
              toalPrice = grp.Sum(b => b.price) //3
          })
          .Where(y => y.totalPrice < 2000); //4

1- 按配方 ID 分组

2- 选择结果以获取每个唯一配方 ID 的不同实体

3- 在这里您可以为每个唯一的 recipeID 求和(通过 y.Key==grouping key 获得)

4- 过滤结果(将 2000 替换为您的实际阈值)

【讨论】:

  • 是否可以添加 name = y.Key 并让它自动从 Key 中提取名称?
  • 由于您是按recipeID 分组的,因此您有一组对象链接到一个唯一的recipeID,但是您可以选择第一个对象的名称,假设它对于整个组都是相同的。我将编辑我给出的示例
  • 哦,如果我仍然需要提取这些数据,我可以将它与配方表连接起来,我猜?
  • 好吧,你不需要它,因为它已经在最初的 join 语句中完成了。如果您需要配方中的其他数据,您可以使用为 Name 描述的相同解决方案(将其添加到 select new 语句的单独字段中,然后在分组后选择最终值)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多