将 2 个数据行加入一行 C# [英] join 2 datarow rows into one row C#
问题描述
虽然我知道我可以通过 sql 连接 2 行,但我的程序不使用它我有 2 个数据表,我取每一行,与另一个表上的行进行比较,并希望从中进行连接
while i know i can make a join of 2 rows via sql, my program doesn't use it i have 2 datatables and i take each row, compare to the rows on the other table and want to make a join out of it
public DataTable joinTables (DataTable t1, DataTable t2)
{
DataTable joinTable = new DataTable();
foreach (DataRow r1 in t1.Rows)
{
foreach (DataRow r2 in t2.Rows)
{
///if (....)
joinTable.ImportRow(joinRows(r1,r2));
}
}
return joinTable;
}
public DataRow joinRows (DataRow r1, DataRow r2)
{
DataRow joinRow = new DataRow();
///....
return joinRow;
}
推荐答案
我认为你可能大大低估了你正在寻找的东西的复杂性,但这里有一些代码可以做到,但它有一些主要的假设我会讨论.
I think you may have vastly underestimated the complexity of what you're looking for, but here is some code that will do it, but it has some major assumptions I'll discuss.
public DataTable joinTables (DataTable t1, DataTable t2)
{
DataTable t = new DataTable();
AddColumns(t1, t);
AddColumns(t2, t);
for (int i = 0; i < t1.Rows; i++)
{
DataRow newRow = t.NewRow();
for (int j = 0; j < t1.Columns.Count; j++)
{
SetMergedRowValue(t1.Rows[i], newRow, j);
SetMergedRowValue(t2.Rows[i], newRow, j);
}
t.Rows.Add(newRow);
}
t.AcceptChanges();
}
private void AddColumns(DataTable source, DataTable target)
{
foreach (DataColumn c in source.Columns)
{
target.Columns.Add(string.Format("{0}_{1}", source.TableName, c.ColumnName), c.DataType);
}
}
private void SetMergedRowValue(DataRow source, DataRow target, int index)
{
var columnName = string.Format("{0}_{1}", source.Table.TableName, source.Table.Columns[index]);
target[columnName] = source[index];
}
假设
- 每个
DataTable
都有相同的行数. - 那些
DataTable
对象中的行按照您希望它们按索引合并的顺序进行排序.
- Each
DataTable
has the same number of rows. - The rows in those
DataTable
objects are sorted in the order you want them merged by index.
这些假设很重要.简而言之,虽然这会产生预期的结果,但我不确定它真的你正在寻找什么,我不确定你真的确定你是什么'重新寻找.
These assumptions are major. In short, though this produces the desired outcome, I'm unsure it's really what you're looking for, and I'm unsure you're really sure what you're looking for.
这篇关于将 2 个数据行加入一行 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!