score:9

Accepted answer

so, if flag is false you need all jhoms, and if flag is true you need only the jhoms in the it department

this condition

!flag || (e.field<string>("employeedepartment") == "it"

satisfies that criterion (it's always true if flag is false, etc..), so the query will become:

from e in employee    
where e.field<string>("employeename") == "jhom"
  && (!flag || (e.field<string>("employeedepartment") == "it")
select e.field<string>("employeeid") 

also, this e.field<string>("employeeid") business, smells like softcoding, might take a look into that. i guess

from e in employee    
where e.employeename == "jhom"
  && (!flag || (e.employeedepartment == "it")
select e.employeeid

would be more compact and less prone to typing errors.


edit: this answer works for this particular scenario. if you have lots of this kinds of queries, by all means investingate the patterns proposed in the other answers.

score:0

from e in employee    
where e.field<string>("employeename") == "jhom" &&
(!flag || e.field<string>("employeedepartment") == "it")
select e.field<string>("employeeid") 

score:0

you can call linq methods explicitly and chain them conditionally.

public ienumerable<string> filteremployees (ienumerable<employee> source, bool restrictdepartment)
{
    var query = source.where (e => e.field<string>("employeename") == "jhom");

    if (restrictdepartment) // btw, there's no need for "== true"
        query = query.where (e => e.field<string>("employeedepartment") == "it");

    return query.select (e => e.field<string>("employeeid"));
}

score:2

you can chain methods :

public void test(bool flag)
{
   var res = employee.where( x => x.employeename = "jhom" );

   if (flag)
   {
       res = res.where( x => x.employeedepartment == "it")
   }

   var id = res.select(x => x.employeeid );
}

score:12

please check out the full blog post: dynamic query with linq

there are two options you can use:

dynamic linq library

string condition = string.empty;
if (!string.isnullorempty(txtname.text))
    condition = string.format("name.startswith(\"{0}\")", txtname.text);

employeedatacontext edb = new employeedatacontext();
if(condition != string.empty)
{
  var emp = edb.employees.where(condition);
 ///do the task you wnat
}
else
{
 //do the task you want 
}

predicate builder

predicate builder works similar to dynamic linq library but it is type safe:

var predicate = predicatebuilder.true<employee>();

if(!string.isnullorempty(txtaddress.text))
    predicate = predicate.and(e1 => e1.address.contains(txtaddress.text));

employeedatacontext edb= new employeedatacontext();
var emp = edb.employees.where(predicate);

difference between above library:

  • predicatebuilder allows to build typesafe dynamic queries.
  • dynamic linq library allows to build queries with dynamic where and orderby clauses specified using strings.

Related Query

More Query from same tag