我想检查一个 DataTable 中的 DataRow 是否存在于另一个 DataTable 中。
我有两个数据表。将有一些相同的 DataRows 存在于两者中。 如果我知道每次都会有哪些列,这会很容易,但我不知道。使用类似...的方法
datatable.Rows[i].Field <String> columnName);
将不起作用,因为该字段可以是整数、字符串或日期/时间。但是我知道这两个文件共享相同的列名。
我的代码是零零碎碎的,但到目前为止它看起来是这样的。现在我生成了一个列名列表,仅此而已。
for (var h = 0; h < origDbfFile.datatable.Columns.Count; h++) {
columnNames.Add(origDbfFile.datatable.Columns[h].ColumnName);
}
我正在进行循环噩梦,如果有人能找到更简洁的解决方案,将不胜感激!
for (int g = 0; g < origDbfFile.dataset.Tables[0].Rows.Count; g++)
{
for (int h = 0; i < modDbfFile.dataset.Tables[0].Columns.Count; h++)
{
foreach (String columnName in columnNames)
{
String rowValue = origDbfFile.dataset.Tables[0].Rows[g].Field<String>(Convert.ToString(columnName));
//test data
result += "Column name:  : " + columnName + "<br/>";
result += "Value " + rowValue + "<br/><br/>";
//if logic will go below
}
}
}
最佳答案
假设您对行值的装箱/拆箱和值/引用类型没有任何问题,您的代码几乎就是您在给定情况下所能做的所有事情。
当然,如果你喜欢 linq 和扩展方法,你可以让它变得更漂亮
public static class DataRowExtensions
{
public static int IndexIn(this DataRow thisRow, DataTable table)
{
return table.Rows
.OfType<DataRow>()
.Select((row, i) => new { row, index = i + 1 })
.Where(pair => EqCondition(thisRow, pair.row))
.Select(pair => pair.index)
.FirstOrDefault() - 1;
}
public static bool EqCondition(DataRow row1, DataRow row2)
{
// check for the equality of row values
return true;
}
}
...
for (int i = 0; i < tab1.Rows.Count; i++)
{
var index = tab1.Rows[i].IndexIn(tab2);
if (index < 0)
{
Console.WriteLine("The row at index {0} was not found in second table", i);
}
else
{
Console.WriteLine("The row at index {0} was found in second table at index", i, index);
}
}
但除了在找到第一个匹配后中断之外,代码完全相同。
我的建议是使用 ids 相等性,请记住,大多数时候数据来自具有索引的数据源,您可能会发现自己处于这种情况。
附言。在你的第二个 for 你有 2 个错误
- 你声明了 h 但使用了 i
- 我想你应该使用 .Rows.Count
关于c#:检查数据行是否存在于具有动态列的不同数据表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778869/