添Schmelter的回答https://stackoverflow.com/a/8472044/26877
public DataTable GroupBy(string i_sGroupByColumn, string i_sAggregateColumn, DataTable i_dSourceTable)
{
DataView dv = new DataView(i_dSourceTable);
//getting distinct values for group column
DataTable dtGroup = dv.ToTable(true, new string[] { i_sGroupByColumn });
//adding column for the row count
dtGroup.Columns.Add("Count", typeof(int));
//looping thru distinct values for the group, counting
foreach (DataRow dr in dtGroup.Rows) {
dr["Count"] = i_dSourceTable.Compute("Count(" + i_sAggregateColumn + ")", i_sGroupByColumn + " = '" + dr[i_sGroupByColumn] + "'");
}
//returning grouped/counted result
return dtGroup;
}
例子:
DataTable desiredResult = GroupBy("TeamID", "MemberID", dt);
來源
2016-04-19 17:23:26
JJS
你不能。改用LINQ。 – SLaks
你不能通過PK字段進行分組... – Baral
我想用什麼,但是我想返回一個DataTable對象。 –