1

I want to apply 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

3
  • are you guaranteed to always have a condition? or you want the condition only if the user specifies it? Commented Mar 18, 2011 at 13:25
  • Yes i want to apply if user specify condition otherwise show all. Commented Mar 18, 2011 at 13:26
  • stackoverflow.com/questions/848415/linq-dynamic-where-clause Commented Mar 18, 2011 at 13:32

2 Answers 2

4
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
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

I think expression trees are overkill for this
Agreed, but if Franz ends up doing something like a search function where the user selects the field to search as well as the condition, then an expression tree would be the answer
var linq = Post.Where(condition).SingleOrDefault(); This line doesnot compile it gives error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.