Could you please check the following what is wrong in this.
I need union of this but it returns 6 record instead of 5(because “Amir” occurs two times)
DataTable dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("Name"));
dt1.Rows.Add(dt1.NewRow()["Name"] = "Imran");
dt1.Rows.Add(dt1.NewRow()["Name"] = "Amir");
dt1.Rows.Add(dt1.NewRow()["Name"] = "Asif");
DataTable dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("Name"));
dt2.Rows.Add(dt2.NewRow()["Name"] = "Tandulkar");
dt2.Rows.Add(dt2.NewRow()["Name"] = "Amir");
dt2.Rows.Add(dt2.NewRow()["Name"] = "Sheqwag");
DataTable dtUnion = dt1.AsEnumerable()
.Union(dt2.AsEnumerable()).CopyToDataTable<DataRow>();
The problem here is that Linq does not know that you want to compare the
Name. Instead it does what it does for all object types it compares the hash which is different for two different instances.What you need todo is tell the Union method how to compare two items. You can do so by creating a custom
IEqualityComparerthat does compare two data rows the way you want it.Here is a sample implementation:
When calling
Unionyou then need to pass in an instance of this comparer:See here for more info:
http://msdn.microsoft.com/en-us/library/bb358407.aspx
Word of advice:
Linq is best with customized data classes, which
DataRowis not . It’s best to have an actual Name property on the class, only then Linq can really shine.If you don’t need the flexibility of dynamic schema you should stay away from
DataTableand implement custom classes that resemble exactly what you need, sinceDataTableis extremely bloated and slow.