简体   繁体   English

字符串变量linq查询中的列名

[英]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. 我感谢您的帮助。

Hello I could resolve it by doing this: 您好,我可以这样解决:

First I Installed the NuGet Package System.Linq.Dynamic Check this link 首先我安装了NuGet软件包System.Linq.Dynamic检查此链接

https://www.nuget.org/packages/System.Linq.Dynamic/ 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 谢谢您的帮助

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 其中YourColumnName是您要过滤的列的名称

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 您可以尝试使用从此处下载的 Dynamic Linq库,然后您的查询将类似于

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

but rerformance will not be greatest. 但是重整并不是最大的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM