Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

C# Linq where clause as a variable

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.

thanks,

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.

I cannot use a switch to generate the where clause because there are way to many possibilities.

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.

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

thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

EDIT: If you're using LINQ to Objects, remove the word Expression to create an ordinary delegate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...