Search code examples
c#linqjoindatatablelinq-to-dataset

Multiple on clause in LINQ to DataTable Join Query


So I have two DataTables that have the same schema, but different data. I want to join the two tables together where two fields, id3 and print and the same. How would I write this in LINQ?

Right now, this works and gives no compiler errors:

var singOneJoin =
    from prod in singOneProd.Table.AsEnumerable()
    join agg in singOneAgg.Table.AsEnumerable()
    on prod.Field<string>("print") equals agg.Field<string>("print")
    select new
    {
        print = prod.Field<string>("print")
    };

But what I really want is this:

var singOneJoin =
    from prod in singOneProd.Table.AsEnumerable()
    join agg in singOneAgg.Table.AsEnumerable()
    on (prod.Field<string>("print") equals agg.Field<string>("print") &&
        prod.Field<Int32>("id3") equals agg.Field<Int32><("id3"))
    select new
    {
        print = prod.Field<string>("print")
    };

But this gives me compiler errors.

How do I join these two tables together on both the print and the id3 columns?

Regards,

Kyle


Solution

  • Use anonymous objects to join on multiple fields:

        var singOneJoin =
            from prod in singOneProd.Table.AsEnumerable()
            join agg in singOneAgg.Table.AsEnumerable()
            on new {
                Print = prod.Field<string>("print"),
                Id3 = prod.Field<Int32>("id3")
            } equals new {
                Print = agg.Field<string>("print"),
                Id3 = agg.Field<Int32>("id3")
            } 
            select new {
                print = prod.Field<string>("print")
            };
    

    Keep in mind that anonymous object property names should match.