Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 931
kformeck Avatar asked Nov 06 '13 13:11

kformeck


People also ask

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want: DataTable tempData = (DataTable)grdUsageRecords.

Can we have multiple conditions for on clause?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

Can we use joins in LINQ?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.


1 Answers

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.

like image 71
Sergey Berezovskiy Avatar answered Nov 12 '22 21:11

Sergey Berezovskiy