代码之家  ›  专栏  ›  技术社区  ›  SaaS Developer

C#列表<>按2个值分组

  •  37
  • SaaS Developer  · 技术社区  · 17 年前

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

    4 回复  |  直到 17 年前
        1
  •  56
  •   Omar    13 年前
    var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
                     .Select(group => group.Sum(x => x.ProductCount));
    
        2
  •  16
  •   Todd Langdon    16 年前

    我意识到这个线程很旧,但由于我刚刚在语法上遇到了困难,我想我会发布我的其他发现——你可以在一个查询中返回总和和ID(w/o foreach),如下所示:

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

    对我来说,让它发挥作用的棘手之处在于,显然,这笔钱必须混在一起。..

        3
  •  7
  •   Klas Mellbourn    17 年前

    或者,如果你想得到每个总和的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));
    }
    
        4
  •  -1
  •   AnshuMan SrivAstav    13 年前

    var New1=EmpList。分组依据(z=>z.Age)。OrderBy(员工=>员工主键);

    dataGridView1.DataSource=新1;

    推荐文章