Dynamic where condition in LINQ

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 12:43:43

问题


I have a scenario where I have to use a dynamic where condition in LINQ.

I want something like this:

public void test(bool flag)
{
   from e in employee
   where e.Field<string>("EmployeeName") == "Jhom"
   If (flag == true)
   {
       e.Field<string>("EmployeeDepartment") == "IT"
   }
   select e.Field<string>("EmployeeID")
}

I know we can't use the 'If' in the middle of the Linq query but what is the solution for this?

Please help...


回答1:


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.




回答2:


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.



回答3:


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 );
}



回答4:


from e in employee    
where e.Field<string>("EmployeeName") == "Jhom" &&
(!flag || e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID") 



回答5:


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"));
}


来源:https://stackoverflow.com/questions/5674639/dynamic-where-condition-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!