How to embed string condition in linq query
I want to ap开发者_JAVA技巧ply few conditions in my linq query. My scenario is I am fetching records from a table and if user select some criteria then apply condition according to. So what i want to do is
var linq = from p in Post select p
//now if user apply that condition
string id = "1"; //Here 1 is what user inputs
string condition = where p.id == id
//then it executes query like this
linq = from p in Post condition select p
Can i do this in linq if yes then how
var linq = from p in Post select p;
//now if user apply that condition
string id = "1"; //Here 1 is what user inputs
if (!String.IsNullOrEmpty(id))
{
linq = linq.Where(p => p.id == id);
}
return linq.ToList(); // or whatever you want to do with it at this point
You will probably want to look into dynamic linq or depending on how complex you want to make the condition use expression trees
You might want to try:
string id = "1";
string condition = "p.id == " + id;
var linq = from p in Post
where (condition)
select p;
or with a lambda:
string id = "1";
string condition = "p => p.id == " + id;
var linq = Post.Where(condition).SingleOrDefault();
See the following:
Scott Gu's post on Dynamic Linq
Querying Entity with LINQ using Dyanmic Field Name
Basics of Linq Expression Trees
精彩评论