【问题标题】:C# List<> GroupBy 2 ValuesC# List<> GroupBy 2 个值
【发布时间】:2010-09-26 16:37:28
【问题描述】:

我在 Framework 3.5 上使用 C#。我希望通过两个属性快速分组一个通用列表。为了这个例子,假设我有一个带有 CustomerId、ProductId 和 ProductCount 属性的 Order 类型的列表。如何使用 lambda 表达式获得按 CustomerId 和 ProductId 分组的 ProductCounts 的总和?

【问题讨论】:

    标签: c# linq list ienumerable group-by


    【解决方案1】:

    var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);

    dataGridView1.DataSource = New1;

    【讨论】:

    • 此答案似乎不适用于该问题。
    【解决方案2】:
    var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
                     .Select(group => group.Sum(x => x.ProductCount));
    

    【讨论】:

      【解决方案3】:

      我意识到这个线程已经很老了,但由于我只是在这个语法上苦苦挣扎,我想我会发布我的额外发现 - 你可以在一个查询中返回总和和 ID(不带 foreach),如下所示:

      var sums = Orders
                  .GroupBy(x => new { x.CustomerID, x.ProductID })
                  .Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});
      

      让我工作的棘手部分是总和必须是别名,显然......

      【讨论】:

      • 我意识到这个答案已经很老了,但如果有人想知道为什么别名是必要的,属性会生成隐式字段名称,但方法不会。
      【解决方案4】:

      或者,如果您想获取每个总和的 ID,您可以这样做

      var customerAndProductGroups =
          from order in Orders
          orderby order.CustomerID, order.ProductID // orderby not necessary, but neater
          group order by new { order.CustomerID, order.ProductID };
      
      foreach (var customerAndProductGroup in customerAndProductGroups)
      {
          Console.WriteLine("Customer {0} has ordered product {1} for a total count of {2}",
              customerAndProductGroup.Key.CustomerID,
              customerAndProductGroup.Key.ProductID,
              customerAndProductGroup.Sum(item => item.ProductCount));
      }
      

      【讨论】:

        猜你喜欢
        • 2020-05-27
        • 2023-01-11
        • 2021-11-01
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 2022-12-05
        相关资源
        最近更新 更多