0

i am using a CustomDataRowEqualityComparer() to compare 2 datatables with different number of columns but they share some columns:

var result= maindatatable.AsEnumerable().Except(dt.AsEnumerable(), new CustomDataRowEqualityComparer()).CopyToDataTable();

how can i make the result datatable contain only the columns in dt?, in the aboVe contex the

result datatable have the columns of the maindatatable

Here is my comparer class

public class CustomDataRowEqualityComparer : IEqualityComparer<DataRow>
    {
        public bool Equals(DataRow x, DataRow y)
        {
            return ((int)x["id"] == (int)y["id"]);
        }

        public int GetHashCode(DataRow obj)
        {
            return ((int)obj["id"]);
        }

    }

it returns all rows in maindatatable that doesnt exist in dt

user1590636
  • 1,174
  • 6
  • 26
  • 56
  • 1
    Use `DataTable.Merge`. Have a look at my custom implementation which allows to union tables on a named column(like your `id`): http://stackoverflow.com/questions/12278978/combining-n-datatables-into-a-single-datatable/12284003#12284003 I guess that it's what you want here too. – Tim Schmelter Mar 19 '13 at 11:27
  • @TimSchmelter not exactly, all rows in dt exist in main datatable, in the result datatable i want to select rows from maindatatable that doesnt exist in dt, the code i attached is working fine but i am not sure how to select te columns i want – user1590636 Mar 19 '13 at 11:47

1 Answers1

1

So you don't know how to return the main-table with all rows that are not in dt but with columns of dt.

In general, you cannot select rows from maintable with columns from another DataTable. Therefore you have to fill a new instance of dt(use dt.Clone() to create all columns) with these rows.

So for example(assuming that the columns of table dt exist also in maintable but not vice-versa):

var result = maindatatable.AsEnumerable()
    .Except(dt.AsEnumerable(), new CustomDataRowEqualityComparer());
var dt2 = dt.Clone();
foreach(DataRow mainRow in result)
{
    var newRow = dt2.Rows.Add();
    foreach (DataColumn col in dt2.Columns)
        newRow[col] = mainRow[col.ColumnName];
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939