假設我有一個通話記錄資料表,其中每一行代表一個通話,其中包含以下列:AccountNumber1、AccountNumber2、AccountListDate、AccountDisposition
我想要 GroupBy 列 AccountNumber1 并想要一個具有相同列 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 的資料表。我如何獲得上面描述的其他列?我將不勝感激任何幫助。謝謝你。
uj5u.com熱心網友回復:
沒有魔法,您需要使用回圈并使用新列初始化新表:
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());
}
這從似乎需要的每個組的第一行中獲取任意值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314648.html
上一篇:在基類方法中參考繼承類?
下一篇:填充自定義型別串列中的空格
