1

I'm using LINQ to join 2 datatables:

var JoinResult = (from p in WZdt.AsEnumerable()
                          join t in WZIdt.AsEnumerable()
                          on p.Field<string>("ID") equals t.Field<string>("ID")
                          select new
                          {
                              p,
                              t
                          }).ToList();

WZdt and WZIdt are DataTables. Normally, when wanted to specify columns I would write something like this:

var JoinResult = (from p in WZdt.AsEnumerable()
                              join t in WZIdt.AsEnumerable()
                              on p.Field<string>("ID") equals t.Field<string>("ID")
                              select new
                              {
                              FileNo = p.Field<string>("FileNo"),
                              Title = p.Field<string>("Title"),
                              M1 = t.Field<int?>("M1"),
                              RecCount = t.Field<int?>("RecCount")
                              }).ToList();

But those source datatables are created dynamically based on some logic, so they can differ when it comes to Columns they have. I would like to apply similiar logic to the select part of LINQ, but I don't know how. Can I construct array of columns somehow, like [p.FileNo, p.Title, t.M1, t.RecCount] ? Or any other way?

PRHMN
  • 109
  • 3
  • 13
  • And what are you going to do with JoinResult after than? – Evk Feb 26 '18 at 12:54
  • I'm mapping it to a DataTable using LINQResultToDataTable found somewhere on the Web. Anyway, when LINQ has those p and t in SELECT, resulting Datatable has 2 columns, each type of DataRow – PRHMN Feb 26 '18 at 12:58
  • It's not clear what you're asking. You want to keep it flexible but at the same time want specific properties in a new anonymous type (for field names like FileNo, Title, etc). That's a contradiction as you'd have to update those Linq queries if data changes. – derloopkat Feb 26 '18 at 14:22
  • I want to determine columns to return from both p and t datatables based on some logic. Let's say that at the runtime I'd like to return FileNo from p and Title from t. Is there any way to put this kind of flesibility to LINQ select instead of listing them explicitly? I don't know how to put it more clearly, sorry :) – PRHMN Feb 26 '18 at 14:53
  • If there’s a way of telling the linq query to return all columns from both datatables that would work as well – PRHMN Feb 26 '18 at 15:33
  • Your original query `select new { p, t }` returns all columns from both datatables as two separate `DataRow`s. You could use a `Dictionary` or `ExpandoObject` instead of an anonymous object at the expense of some performance. – NetMage Feb 26 '18 at 20:28
  • How do I do that? Do mean returning Dictionary/ExpandoObject in LINQ select? Or do I expand those after constructing LINQ with 2 datarows? – PRHMN Feb 27 '18 at 07:27

0 Answers0