如何比较c#中的数据表 [英] How to compare datatables in c#
问题描述
Hi
我们正在为此示例导出2个不同数据库之间的数据:Teradata - > Cloudera。
我们需要的是确保每一行都被导出。
所以我使用C#创建一个函数,从Teradata中提取数据并将其存储到DataTable中,其他函数从Cloudera中提取数据并将其存储到DataTable中。
我希望能够比较两个数据表并获取提取时是否缺少数据。
我尝试了什么:
我尝试合并两个数据表,迭代每一行,迭代for循环。但是需要花费大量时间来比较两个数据表
DataTables没有用于复杂比较操作的内置方法,您需要自定义您的解决方案,可能是循环在嵌套的foreach循环中的两个DataTable上。
通过下面的代码片段查看它是否有效
static void CompareRows(DataTable table1,DataTable table2)
{
foreach (DataRow row1 in table1.Rows)
{
foreach (DataRow row2 in table2.Rows)
{
var array1 = row1。 ItemArray;
var array2 = row2.ItemArray;
if (array1.SequenceEqual(array2))
{
Console.WriteLine( 等于:{0} {1},
row1 [ col1],row2 [ col1 跨度>]);
}
else
{
Console.WriteLine( 不相等:{0} {1},
row1 [ col1],row2 [ col1] );
}
}
}
有很多方法可以比较数据。
最简单的方法是使用SQL工具在服务器端比较它们,请参阅:如何:比较和同步两个数据库的数据 [ ^ ]
最糟糕的解决方案是在客户端比较它们,特别是当数据库的大小很大时...
我建议你读这个:比较DataRows(LINQ to DataSet) [ ^ ]
Google图书: LINQ For Dummies - John Paul Mueller [ ^ ] br />
注意: Linq解决方案可能不是最好的选择,因为它的性能。因此,使用两个for循环可能比Linq解决方案更快。
决定属于你。
只计算每个数据表的行数,然后比较行数。
Hi
We are exporting data between 2 different databases for this example: Teradata -> Cloudera.
What we need is to make sure that every single row was exported.
So I create a function using C# that extract the data from Teradata and store it into a DataTable, other function that extract the data from Cloudera and store it into a DataTable.
I want to be able to compare both datatables and get if there is missing data on the extraction.
What I have tried:
I have tried merge both datatables, iterate for each row, iterate with for loop. But it take a lot of time to compare both datatables
DataTables have no built-in methods for complicated comparison operations, You need to customize your solutions, may be loop over both DataTables in nested foreach-loops.
go through below snippet, see if it works
static void CompareRows(DataTable table1, DataTable table2) { foreach (DataRow row1 in table1.Rows) { foreach (DataRow row2 in table2.Rows) { var array1 = row1.ItemArray; var array2 = row2.ItemArray; if (array1.SequenceEqual(array2)) { Console.WriteLine("Equal: {0} {1}", row1["col1"], row2["col1"]); } else { Console.WriteLine("Not equal: {0} {1}", row1["col1"], row2["col1"]); } } }
There's numbers of ways to compare data.
The simplest way is to compare them on server's side using SQL tools, see: How to: Compare and Synchronize the Data of Two Databases[^]
The worst solution is to compare them on client's side, especially when the size of databases is large...
I'd suggest to read this: Comparing DataRows (LINQ to DataSet)[^]
Google book: LINQ For Dummies - John Paul Mueller[^]
Note: Linq solution may not be the best option, because of its performance. So, using two for-loops might be faster than Linq solution.
Decision belongs to you.
just count the number of rows of each datatable then compare number of rows.
这篇关于如何比较c#中的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!