使用字符串代替属性名称(LINQ)

时间:2013-12-20 07:32:36

标签: string linq

我已经能够使用linq从表中获取值。

var q=(from app in context.Applicant 
        where app.ApplicantName=="")

现在我想要的是:

 var q=(from app in context.Applicant 
        where app.stringIhave =="")  // so instead of column name I have string which has same name as column.

是否可以在Select中指定字符串,因为这不确定在每种情况下我会得到什么,我总是需要不同的数据。

有可能这样做吗? 如果不是,那么我会找出别的东西。 的更新 我有一个GlobalString,它保存表的列名。 因此,当我查询该表时,我只从字符串中指定了我想要获取的列值:

var q=(from app in context.Applicants
       where app.ID==1013
       select GlobalString //which is specifying that I want to get value from which column, as column name is not fixed.
 //where GlobalString can have values like: app.FirstName..app.LastName etc

UPDATE1:

var q = context.Applicants.Select("new(it.ApplicantFirstName as FirstName, it.ApplicantLastName as LastName)");

错误讯息:

The query syntax is not valid. Near keyword 'AS'

2 个答案:

答案 0 :(得分:2)

您可以使用Dynamic Linq(可从NuGet获得):

   var q = context.Applicant.Where(app.stringIhave + " = @0", "");

答案 1 :(得分:0)

选择你可以尝试这样的东西

var q = context.Applicant.Select("new(it.FirstName as FirstName, it.LastName as LastName)");

所以你只需要那种格式的构造字符串