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

Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132

2 Answers2

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
Misko
  • 2,044
  • 12
  • 15
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

Community
  • 1
  • 1
Scott Lance
  • 2,239
  • 1
  • 18
  • 19
  • 2
    I think expression trees are overkill for this – Roly Mar 18 '11 at 13:31
  • 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 – Scott Lance Mar 18 '11 at 13:33
  • var linq = Post.Where(condition).SingleOrDefault(); This line doesnot compile it gives error – Fraz Sundal Mar 24 '11 at 17:57