C#LINQ的where子句作为一个变量
我试图让那里的where子句来自变量的LINQ声明。例如:
I am trying to make a LINQ statement where the where clause comes from a variable. For example:
string whereClause = address.zip == 23456;
var x = from something in someList where whereClause;
这可能吗?我似乎无法得到它的工作。
Is this possible? I cannot seem to get it to work.
感谢,
更新 - 我的where子句是预定义的,将根据用户的输入,所以我不ŧ认为这会为我工作。基本上whereClause未在方法构造,它是它执行的LINQ的方法的参数。我没有解释好这里是一个更好的例子:
Update - my where clause is predefined and will be based on user input so I don't think this will work for me. Basically whereClause is not constructed in the method, it is a parameter of the method which does the LINQ. I didn't explain that well here is a better example:
public void doLnq(string whereClause)
{
var x = from something in someList where whereClause;
dowork(x);
}
更新 - 只是为了总结一些建议,并集中一切。
Update - Just to sum up some of the suggestions and centralize everything.
我不能使用一个开关来生成where子句,因为有办法许多可能性。
I cannot use a switch to generate the where clause because there are way to many possibilities.
这几个你已经张贴看上去很有希望,但我麻烦相关LINQ to SQL的例子,我的LINQ to对象有问题的动态LINQ职。
The dynamic linq post that a few of you have posted does look promising but i am having trouble related the linq to sql example to my linq to objects problem.
和@sLaks通过MSDN HTTP照看: //msdn.microsoft.com/en-us/library/bb353734.aspx 我有麻烦搞清楚你的意思是使用AsQueryable已
and @sLaks after looking through msdn http://msdn.microsoft.com/en-us/library/bb353734.aspx I am having trouble figuring out where you meant to use AsQueryable
谢谢,
您需要装配一个表达式来; Func键< T,BOOL>>
,并把它传递给其中()
扩展方法:
You need to assembly an Expression<Func<T, bool>>
and pass it to the Where()
extension method:
Expression<Func<T, bool>> whereClause = a => a.zip == 23456;
var x = frSomeList.Where(whereClause);
修改:如果您使用LINQ到对象,删除该单词表达式
来创建一个普通的委托。
EDIT: If you're using LINQ to Objects, remove the word Expression
to create an ordinary delegate.