none
How to use LINQ for 2 Data Tables at same time RRS feed

  • Question

  • Hi,

    I have 2 data tables. DataTable1 and DataTable2

    I want to compare the each column for each row between DataTable1 and DataTable2. The two DataTables have same column fields but the values will be different except some IDs. These IDs may/maynot become same occasionally.

    I am using the code as shown below:

    var query = from DT1 in DataTable1.AsEnumerable()
                    from DT2 in DataTable2.AsEnumerable()
                    where DT1.Field<string>("ID") == variable1 && DT2 .Field<string>("ID") == variable2
                    select
    new
                     {
                        DT1,
                        DT2
                     };

    foreach(var items in query)
    {  
      
    if (DT1.Field<string>("firstname") == DT2.Field<string>("firstname"))
          {
                // here i am getting error like 
                    Error 2 'AnonymousType#1' does not contain a definition for 'Field' and the
                    best extension method overload 'System.Data.DataRowExtensions.Field<T>(System.Data.DataRow, string)' has some invalid arguments .......

                // Another Error is DT2 is not in the Context...........

          }
    }

    How can I do that ?

    Tuesday, March 24, 2009 3:40 AM

All replies

  • Try,

    foreach(var items in query)
    {  
      
    if (items.DT1.Field<string>("firstname") == items.DT2.Field<string>("firstname"))
          {
          }
    }

    Thanks and Regards,
    Vijay Pandurangan
    Tuesday, April 28, 2009 1:34 PM
  • Or simply create a DataRelation object between the two and then querying either or both is a snap.

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Wednesday, April 29, 2009 2:52 AM