8

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

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
kformeck
  • 1,703
  • 5
  • 22
  • 43
  • 2
    possible duplicate of [LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?](http://stackoverflow.com/questions/5307731/linq-to-sql-multiple-joins-on-multiple-columns-is-this-possible) – J0HN Nov 06 '13 at 13:49

1 Answers1

15

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.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459