3

Hi I'm trying to compare two datatable through Linq. But I get this exception:

Specific cast is invalid

Please help me as I am new to Linq. This is the code I'm using:

var matched1 = from table1 in dtAvailableStores.AsEnumerable()
               join table2 in dtControlStores.AsEnumerable() 
               on table1.Field<int>("STORE_NBR") 
               equals table2.Field<int>("STORE_NBR")
               select table1;

Here STORE_NBR is a string value.

Omar
  • 16,329
  • 10
  • 48
  • 66
Divya
  • 979
  • 3
  • 13
  • 18

2 Answers2

3

You can have a fairly good idea with this piece of code:

var qry1 = datatable1.AsEnumerable().Select(a => new { MobileNo = a["ID"].ToString() });
var qry2 = datatable2.AsEnumerable().Select(b => new { MobileNo = b["ID"].ToString() });

var exceptAB = qry1.Except(qry2);

DataTable dtMisMatch = (from a in datatable1.AsEnumerable() join ab in exceptAB on a["ID"].ToString() equals ab.MobileNo select a).CopyToDataTable();

References:

  1. Compare two datatable using LINQ Query
  2. Compare two DataTables for differences in C#?
Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
2

This would happen if that field isn't actually an int.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964