【问题标题】:Group by its count from datatable in C# [closed]按 C# 中的数据表中的计数分组[关闭]
【发布时间】:2021-01-26 01:47:41
【问题描述】:

我是 linq 的新手。

我有一个数据表,需要使用 linq 根据另一列更新一列。

我的价值

customer | value1  |  value2  | count
---------------------------------------- 
   A     |   sda   |  sdas    |  0
   A     |   sda   |  sdas    |  0
   B     |   sda   |  sdas    |  0
   B     |   sda   |  sdas    |  0
   B     |   sda   |  sdas    |  0
   C     |   sda   |  sdas    |  0

期望值

customer | value1  |  value2  | count
---------------------------------------- 
   A     |   sda   |  sdas    |  2
   A     |   sda   |  sdas    |  2
   B     |   sda   |  sdas    |  3
   B     |   sda   |  sdas    |  3
   B     |   sda   |  sdas    |  3
   C     |   sda   |  sdas    |  1

您能建议我上述数据表所需的 linq 吗?

【问题讨论】:

  • 那么到目前为止,您尝试了什么?请向我们展示您的代码并解释您在哪里卡住了。
  • I have a datatable and need to update a column according to another column using linq 这个DataTable 是怎么填充的,是绑定到源的吗?您能否更新您的帖子以包含您尝试过的内容和无效的内容?

标签: c# .net linq c#-4.0


【解决方案1】:

您没有提供代码,但我认为您正在寻找这样的东西:(假设您的 DataTable 被称为“dt”)

foreach(DataRow dr in dt.Rows) // loop whole table
{
   //Find count of rows which has same value
    var count = dt.AsEnumerable().Where(i=> i["customer"] == dr["customer"] && i["value1"] == dr["value1"] && i["value2"] == dr["value2"]).Count();
    
    /Then update count column
    dr["count"] = count;
}

您可以遵循的另一种方法是 GroupBy 数据表中的多个列。

 dt.AsEnumerable()
    .GroupBy(g => new {Customer = g["customer"], Value1 = g["value1"], Value2= g["value2"]})
    .Select(g=> 
    {
        var newRow = dtNew.NewRow();
        
        row["customer"] = g.Key.Customer;
        row["value1"] = g.Key.Value1;
        row["value2"] = g.Key.Value2;
        row["count"] = g.Count();
        
        return newRow;
    })
    .CopyToDataTable();

见:How do I use SELECT GROUP BY in DataTable.Select(Expression)?

【讨论】:

    猜你喜欢
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多