compare datarows of different tables

我与影子孤独终老i 提交于 2019-12-01 06:03:23

问题


I posted a similar query some time ago and decided to trim down the complexity of it to let developers answer my main problem. It could be stated as duplicate, but still I want to post it as editing the previous post did not yield much result.

I have 2 datatables: dataTable1 and dataTable2. Both have 1 row with same entries. For eg. columns in both the datatables are Name, Class, Subject. Now both row of both the dataTable are same with values ("John", "5", "Science"). Now I want to compare thses 2 rows if they they have same entries or not. I tried for:

if(dataTable1.Rows[0].GetHashCode() == dataTable2.Rows[0].GetHashCode()) 
{ 
    // Result is false (but I expected it to be true) 
} 

And also tried:

if(dataTable1.Rows[0].ItemArray == dataTable2.Rows[0].ItemArray) 
{ 
    // Result is false (but I expected it to be true) 
} 

I want to avoid loops to do it, but if needed thats fine. I just want to compare the 2 rows of 2 different dataTables that if their entries are same or not. And I am not sure how to proceed. Thanks.


回答1:


var result= dataTable1.AsEnumerable().Intersect(dataTable2.AsEnumerable(),
                                                    DataRowComparer.Default);

it returns the records that are in both the table

more info at:

http://msdn.microsoft.com/en-us/library/bb386998.aspx




回答2:


You could use the Equals method of the DataRowComparer class to compare the rows.




回答3:


Using SequenceEqual to compare two data row as in the following example

foreach (DataRow dr in datatable1.Rows)
    foreach (DataRow dr2 in datatable2.Rows)
    {
        if (dr.ItemArray.SequenceEqual(dr2.ItemArray))
        {
            MessageBox.Show("dr = dr2");
            //statement                                    
        }
        else
        {
            MessageBox.Show("dr != dr2");
            //statement
        }
    }



回答4:


For simplicity, I would normally just cast the item in the ItemArray to a string and compare them that way.
From what I remember, using the GetHashCode will not bring out the same result as you will find many others will say.
If you have a large number of rows, then you could try creating a class that inherits from DataRow and override the Equals method. For example:
class CustomRow : DataRow {

    public override bool Equals(object obj)
    {
        if(obj.GetType() != typeof(CustomRow)) return false;
        for (int i = 0; i < ItemArray.Length; i++)
            if (((CustomRow)obj)[i] != this[i])
                return false;

        return true;
    }
}




回答5:


Another option is:

DataView dv = new DataView(dataTable1); 
dv.Filter = "SQL query to find specific row"

This, naturally, is for every raw you gonna find



来源:https://stackoverflow.com/questions/9064485/compare-datarows-of-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!