c# - 汇总datatable中的重复行

时间:2014-11-27 09:48:22

标签: c#

我有一张桌子,我想总结一下重复的行:

|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);
        }

2 个答案:

答案 0 :(得分:2)

这是你用字典做的。基本上你从" name"创建一个字典。到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

答案 1 :(得分:0)

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

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