我如何在此 DataTable 上按一列分组

How do I GroupBy one column on this DataTable

假设我有一个通话记录数据表,其中每一行代表以下列进行的通话: AccountNumber1、AccountNumber2、AccountListDate、AccountDisposition

我想要 GroupBy 列 AccountNumber1 并想要一个具有相同列的新 DataTable + 1 个附加列 NumCalls,这将是每个 AccountNumber1 的调用次数。

GroupBy 后的新数据表: AccountNumber1、AccountNumber2、AccountListDate、AccountDisposition、NumCalls

到目前为止我有以下内容:

table.AsEnumerable()
    .GroupBy(x => x.Field<int>("AccountNumber1"))
    .Select(x => new { x.Key.AccountNumber1, NumCalls = x.Count() })
    .CopyToDataTable()

这为我提供了一个只有两列 AccountNumber1 和 NumCalls 的 DataTable。我如何获得上面描述的其他列?我将不胜感激任何帮助。谢谢。

没有魔法,您需要使用循环并使用新列初始化新的 table:

DataTable tblResult = table.Clone();
tblResult.Columns.Add("NumCalls", typeof(int));
var query = table.AsEnumerable().GroupBy(r => r.Field<string>("AccountNumber1"));
foreach (var group in query)
{
    DataRow newRow = tblResult.Rows.Add();
    DataRow firstOfGroup = group.First();
    newRow.SetField<string>("AccountNumber1", group.Key);
    newRow.SetField<string>("AccountNumber2", firstOfGroup.Field<string>("AccountNumber2"));
    newRow.SetField<DateTime>("AccountListDate", firstOfGroup.Field<DateTime>("AccountListDate"));
    newRow.SetField<string>("AccountDisposition", firstOfGroup.Field<string>("AccountDisposition"));
    newRow.SetField<int>("NumCalls", group.Count());
}

这似乎需要从每个组的第一行中获取任意值。