0

I am in need to join two data tables and retrieve some columns(which will chosen dynamically) from the joined table. I have used the LINQ query to perform joins but i was not able to select columns columns dynamically.

The code is:

    var q = (from pd in tableOne.AsEnumerable()
                 join od in tableTwo.AsEnumerable() on pd.Field<string>(leftTableColumn) equals od.Field<string>(rightTableColumn)
                 select new
                 {
                     Column1=pd.Field<dynamic>(reuiredColumn1),
                     Column2=od.Field<dynamic>(requireColumn2)

                 });

here tableOne and tableTwo are Data Tables. The problem here is I can always able to get only two columns(column1,column2) as per the query.But i am in need to form the select query dynamically based on the user selection.

Can anyone please share any idea regards how to achieve this result?

Vinod Kumar
  • 408
  • 4
  • 18

2 Answers2

0

What are you trying to achieve? A data grid with variable user defined columns? Is this Entity Framework or Linq-to-SQL?

Easy version

  • If there is not hundreds of columns, I'd just load all the columns and hide only the columns i want to show in the GUI.

Hard version

  • If you really need to load only a few columns from the DB. I'd recommend using the Extension methods version of LINQ (i.e. tableOne.Select(lambda expression) ) and create the Anonymous type as an expression dynamically.
Community
  • 1
  • 1
Petr Vávro
  • 1,506
  • 1
  • 10
  • 12
  • OP is using `DataTable`s and [DataTableExtensions.AsEnumerable](https://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable(v=vs.110).aspx) – Ivan Stoev Apr 05 '16 at 08:07
  • Thanks didn't get that, I will delete the part about the AsEnumerable method then. – Petr Vávro Apr 05 '16 at 08:15
0

If i understand correctly. You can once select your main tables and then based on some conditions select the columns that you want. Here is the untested code

 var q = (from pd in tableOne
                 join od in tableTwo on pd.Field equals od.Field
                 select new
                 {
                     pd, 
                     od
                 });

if(somecondition)
{
   var q1 = from result in q
        select q.pd.yourcoloumns;
} 
else 
{
    var q1 = from result in q
            select q.od.yourcoloumns;
}

In my example the pd and od are your tables.

Idrees Khan
  • 7,702
  • 18
  • 63
  • 111
  • Regards the following (var q1 = from result in q select q.pd.yourcoloumns;) in your code how to select multiple columns in a same query? I am using like this, var q1 = from result in q select q.Select(i=>i.pd[reuiredColumn1]);...still i able to get only one column at a time. – Vinod Kumar Apr 05 '16 at 09:33
  • with comman seperated `q.Select(i=>i.pd.Coloumns1, i.pd.coloumn2)` put a dot `.` after `pd` or `od` – Idrees Khan Apr 05 '16 at 10:39