我有一个来自数据库的数据表[有 5 列],其中包含组合数据。 我需要在此组合表上调用 group by 并创建 2 个表...一个包含 groupedBy 行,其他包含项目。 在 C# 代码中执行此操作的最快方法是什么? 另外,我在下面编写了为这两个表添加列的代码。这是正确的吗?
这是我的代码:
string colName = "ACCOUNT_ID";
var allRows = combinedTable.AsEnumerable();
var accountRowGroups = allRows.GroupBy(row => row[colName]);
DataTable masterDataTable = new DataTable();
DataTable childPricesDataTable = new DataTable();
// Create the columns
DataColumnCollection pdCols = combinedTable.Columns;
for (int ndx = 0; ndx < pdCols.Count; ndx++)
{
string columnName = pdCols[ndx].ColumnName;
Type type = Type.GetType(pdCols[ndx].DataType.ToString());
masterDataTable.Columns.Add(columnName, type);
childPricesDataTable.Columns.Add(columnName, type);
}
最佳答案
在这里查看类似的问题:How to merge multiple DataTable objects with group by with C# and concatinating duplicate rows?
我同意 duffymo 的观点,用 SQL 而不是内存中的数据来完成。
但是,如果这不是一个选择:
您可以在两个数据表之间添加关系:http://msdn.microsoft.com/en-us/library/ay82azad(v=vs.71).aspx
然后您可以对合并的数据表运行分组依据:http://codecorner.galanter.net/2009/04/20/group-by-and-aggregates-in-net-datatable/
下面是 SQL 团队提供的一个正确示例: http://weblogs.sqlteam.com/davidm/archive/2004/05/20/1351.aspx
public static DataTable GROUPBY(DataTable Table, DataColumn[] Grouping, string[] AggregateExpressions, string[] ExpressionNames, Type[] Types)
{
if (Table.Rows.Count == 0)
return Table;
DataTable table = SQLOps.PROJECT(Table, Grouping);
table.TableName = "GROUPBY";
for (int i = 0; i < ExpressionNames.Length; i++)
{
table.Columns.Add(ExpressionNames[i], Types[i]);
}
foreach (DataRow row in table.Rows)
{
string filter = string.Empty;
for (int i = 0; i < Grouping.Length; i++)
{
//Determine Data Type
string columnname = Grouping[i].ColumnName;
object o = row[columnname];
if (o is string || DBNull.Value == o)
{
filter += columnname + "='" + o.ToString() + "' AND ";
}
else if (o is DateTime)
{
filter += columnname + "=#" + ((DateTime)o).ToLongDateString()
+ " " + ((DateTime)o).ToLongTimeString() + "# AND ";
}
else
filter += columnname + "=" + o.ToString() + " AND ";
}
filter = filter.Substring(0, filter.Length - 5);
for (int i = 0; i < AggregateExpressions.Length; i++)
{
object computed = Table.Compute(AggregateExpressions[i], filter);
row[ExpressionNames[i]] = computed;
}
}
return table;
}
关于c# - 创建数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6898957/