LINQ - if else in LINQ queries - Asked By Shan on 03-Jun-11 02:14 AM

hi,

 I want to write 4 LINQ queries where only I want to change the where condition.
should I write the LINQ query 4 times or is it possible to change the where condition alone in if else.
Riley K replied to Shan on 03-Jun-11 02:17 AM
This might give u some idea

from p in db.products
    select new
    {
        Owner = (p.price > 0 ?  from q in db.Users select q.Name :
from r in db.ExternalUsers select r.Name)
    }
Kirtan Patel replied to Shan on 03-Jun-11 02:21 AM
you have to execute 4 LINQ Queries separately what ever you are talking is like saying you want to execute linq query written as tring variable ( thats called Dynamic LINQ) this type of execution of query is still underdevelopment

here is that project that can do that

http://sourceforge.net/projects/dynamiclinq/

but there is not proper documentation available for this ..so better execute 4 LINQ statements

thanks
Jitendra Faye replied to Shan on 03-Jun-11 02:25 AM
No, you can write only one LINQ query ,

like this

from emp in db.emptable
    where emp.id='1' || emp.id='2'
    select emp;






try this and let me know.



jason rle replied to Shan on 13-Jun-11 03:11 AM
I think you could use standard query operator and lambda expression to do what you describled, please try:

var query = from u
in users select u;
if (condition1)
{
  query = query.Where(e => e.ID > 0);
}
else if (condition2)
{
  query = query.Where(e => e.ID > 0 && e.GroupId > 0);
}
else if (condition3)
{
  query = query.Where(e => e.GroupId > 0);
}
else if (condition4)
{
  query = query.Where(e => e.ID > e.GroupId);
}