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.

3
  • Check out this answer about Dynamic Linq here stackoverflow.com/a/18762412/1804496 and also look at the accepted answer on that question for an example. Commented Jun 2, 2015 at 15:39
  • I can't use namespace System.Linq.Dynamic; Do I have to add a library? Commented Jun 2, 2015 at 15:59
  • Yes, the link was in the blog post if you read it msdn.microsoft.com/en-US/vstudio/bb894665.aspx Commented Jun 2, 2015 at 16:13

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for sharing this! For anyone interested, the .NetCore version can be found here: nuget.org/packages/System.Linq.Dynamic.Core
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

1 Comment

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'
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.