Luis Lora
Luis Lora

Reputation: 83

Column Name from string variable linq query

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.

Upvotes: 1

Views: 4434

Answers (3)

Luis Lora
Luis Lora

Reputation: 83

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

Upvotes: 2

Yuri
Yuri

Reputation: 2900

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.

Upvotes: 0

Yuri
Yuri

Reputation: 2900

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

Upvotes: 0

Related Questions