C#LINQ的where子句作为一个变量 [英] C# Linq where clause as a variable

查看:1036
本文介绍了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.

这篇关于C#LINQ的where子句作为一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆