1

Hello I need to select a column in my query with the name stored in a string variable, something like:

string day = "Monday";

result = from w in DataContext.Table
         where w.day == true
         select w.SGL;          

If I do that I got an Syntax error that says 'There is no definition of day or Method'

I appreciate your help.

ekad
  • 14,436
  • 26
  • 44
  • 46
Luis Lora
  • 83
  • 1
  • 9
  • Check out this answer about Dynamic Linq here http://stackoverflow.com/a/18762412/1804496 and also look at the accepted answer on that question for an example. – Zack Jun 02 '15 at 15:39
  • I can't use namespace System.Linq.Dynamic; Do I have to add a library? – Luis Lora Jun 02 '15 at 15:59
  • Yes, the link was in the blog post if you read it https://msdn.microsoft.com/en-US/vstudio/bb894665.aspx – Zack Jun 02 '15 at 16:13

3 Answers3

2

Hello I could resolve it by doing this:

First I Installed the NuGet Package System.Linq.Dynamic Check this link

https://www.nuget.org/packages/System.Linq.Dynamic/

Next add Namespace:

using System.Linq.Dynamic;

And the query goes:

string day = "Monday";

var resultado = DataContext.Table
                   .Where(day + " == true")
                   .Select("SGL");

That's all thanks for your help

Luis Lora
  • 83
  • 1
  • 9
  • Thank you for sharing this! For anyone interested, the .NetCore version can be found here: https://www.nuget.org/packages/System.Linq.Dynamic.Core/ – Hudgi May 23 '19 at 14:20
0

Not sure what you are looking for, but if you are trying to select records where column contains string you need to use this:

string day = "Monday";

result = from w in DataContext.Table
     where w.YourColumnName.Contains(day)
     select w.SGL;      

where YourColumnName is the name of the column you are filtering on

Yuri
  • 2,820
  • 4
  • 28
  • 40
  • In my example the column name is Monday and it stores a bit, there is a Column for each Day (Tuesday, wednesday, ... ) What I need, is to change dynamically the 'YourColumnName' – Luis Lora Jun 02 '15 at 19:04
0

Sorry, dynamically address column names is not possible. Best solution in your case is to use

string day = "Monday";

result = from w in DataContext.Table
 where w.YourColumnName.Contains(day)
 select w.SGL;      
switch (day){
   case "Monday":
      result = from w in DataContext.Table
 where w.Monday == true
 select w.SGL; 
 break;
 //an so on
}

or use strategy pattern to replace switch, but dynamically setting column name - not possible. You can try to use Dynamic Linq library downloaded from here, then your query will look like

var query = DataContext.Table
                         .Where("Monday = 0")

but rerformance will not be greatest.

Yuri
  • 2,820
  • 4
  • 28
  • 40