【问题标题】:c# - Summarizing duplicate rows in datatablec# - 汇总数据表中的重复行
【发布时间】:2014-11-27 09:48:22
【问题描述】:

我有一张表,我想总结重复的行:

|name  | n |   |name  | n |
|------+---|   |------+---|
|leo   | 1 |   |leo   | 3 |
|wayne | 1 |   |wayne | 2 |
|joe   | 1 |   |joe   | 1 |
|wayne | 1 |
|leo   | 1 |
|leo   | 1 |

我可以这样删除,但是如何总结呢?

        ArrayList UniqueRecords = new ArrayList();
        ArrayList DuplicateRecords = new ArrayList();

        foreach (DataRow dRow in table.Rows)
        {
            if (UniqueRecords.Contains(dRow["name"]))
                DuplicateRecords.Add(dRow);
            else
                UniqueRecords.Add(dRow["name"]);
        }

        foreach (DataRow dRow in DuplicateRecords)
        {
            table.Rows.Remove(dRow);
        }

【问题讨论】:

标签: c#


【解决方案1】:

这就是您使用字典的方式。基本上,您创建一个从“名称”到 DataRow 对象的字典,然后总结 DataRows 的“n”属性:

// create intermediate dictionary to group the records
Dictionary<string, DataRow> SummarizedRecords = new Dictionary<string, DataRow>();

// iterate over all records 
foreach(DataRow dRow in table.Rows)
{
  // if the record is in the dictionary already -> sum the "n" value
  if(SummarizedRecords.ContainsKey(dRow["name"]))
  {
    SummarizedRecords[dRow["name"]].n += dRow["n"];
  }
  else
  {
    // otherwise just add the element
    SummarizedRecords[dRow["name"]] = dRow;
  }
}

// transform the dictionary back into a list for further usage
ArrayList<DataRow> summarizedList = SummarizedRecords.Values.ToList();

我认为这可以通过 LINQ 更优雅地完成(1 行代码)。让我再想一想:)

编辑

这是一个 Linq 版本,但是涉及创建新的 DataRow 对象,这可能不是您的意图 - 不知道:

ArrayList<DataRow> summarizedRecords = table.Rows.GroupBy(row => row["name"]) // this line groups the records by "name"
              .Select(group => 
                      {
                        int sum = group.Sum(item => item["n"]);  // this line sums the "n"'s of the group
                        DataRow newRow = new DataRow();  // create a new DataRow object
                        newRow["name"] = group.Key;      // set the "name" (key of the group)
                        newRow["n"] = sum;               // set the "n" to sum
                        return newRow;                   // return that new DataRow
                      })
              .ToList();     // make the resulting enumerable a list

【讨论】:

    【解决方案2】:

    感谢您的回复,另一种变体:

    var result = from row in table.AsEnumerable()
                                 group row by row.Field<string>("Name") into grp
                                 select new
                                 {
                                     name = grp.Key,
                                     n = grp.Count()
                                 };
    

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2018-07-25
      • 2020-08-31
      相关资源
      最近更新 更多