Harshit
Harshit

Reputation: 5157

LINQ join return datatable

I would like to know if it is possible to return a datatable by joining two datatables.

var query = from v in dt1.AsEnumerable()
      join c in dt2.AsEnumerable() on v.Field<int>("ID") equals c.Field<int>("ID")
      where v.Field<string>("col1").Equals("abcd") 
      && (c.Field<string>("col1").Equals("8776") || c.Field<string>("col1").Equals("8775"))
      select new 
{};

I have joined two datatables with various conditions. Is it possible to return a datatable from them with all the rows from both the datatable ?

Upvotes: 2

Views: 538

Answers (1)

Fede
Fede

Reputation: 4016

You can return an anonymous object if the query is going to be evaluated right away, and you don't need to pass it through as a return type nor an argument type of some method.

var query = from v in dt1.AsEnumerable()
      join c in dt2.AsEnumerable() on v.Field<int>("ID") equals c.Field<int>("ID")
      where v.Field<string>("col1").Equals("abcd") 
      && (c.Field<string>("col1").Equals("8776") || c.Field<string>("col1").Equals("8775"))
      select new  { v, c };

And then:

foreach (var result in query) {
    var v = result.v;
    var c = result.c;
    // do your magic here
}

If that's not the case, you can always create a simple struct with the 2 fields, one for each table row.

Upvotes: 1

Related Questions