LINQ 中的动态 where 条件

发布于 2024-11-01 07:45:02 字数 389 浏览 5 评论 0原文

我有一个场景,我必须在 LINQ 中使用动态 where 条件。

我想要这样的东西:

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

我知道我们不能在 Linq 查询中间使用“If”,但是解决方案是什么?

请帮忙...

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

才能让你更想念 2024-11-08 07:45:02

请查看完整的博客文章:使用 Linq 进行动态查询

您可以使用两个选项:

动态 LINQ 库

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 
}

谓词构建器

谓词构建器的工作方式与动态 LINQ 库类似,但它是类型安全的:

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

上述库之间的区别:

  • PredicateBuilder 允许构建类型安全的动态查询
  • 动态 LINQ 库允许使用使用字符串指定的动态Where 和 OrderBy 子句构建查询。

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.
夏了南城 2024-11-08 07:45:02

因此,如果 flagfalse,您需要所有 Jhom,如果 flag 为 true,您只需要 IT 部门的 Jhom。

此条件

!flag || (e.Field<string>("EmployeeDepartment") == "IT"

满足: criteria(如果 flag 为 false,则始终为 true,等等),因此查询将变为:

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

此外,此 e.Field("EmployeeID") 业务,闻起来像 softcoding,可能会看看。我想

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

会更紧凑并且不太容易出现打字错误。


编辑:这个答案适用于这个特定的场景。如果您有很多此类查询,请务必研究其他答案中提出的模式。

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.

聽兲甴掵 2024-11-08 07:45:02

您可以链接方法:

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

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 );
}
尽揽少女心 2024-11-08 07:45:02
from e in employee    
where e.Field<string>("EmployeeName") == "Jhom" &&
(!flag || e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID") 
from e in employee    
where e.Field<string>("EmployeeName") == "Jhom" &&
(!flag || e.Field<string>("EmployeeDepartment") == "IT")
select e.Field<string>("EmployeeID") 
时光瘦了 2024-11-08 07:45:02

您可以显式调用 LINQ 方法并有条件地链接它们。

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

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"));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文