寻找构建Linq动态/条件表达式的简单方法

时间:2013-09-10 20:22:15

标签: c# linq

将表格视为:

表1

  • ID
  • stringfield1
  • stringfield2
  • stringfield3
  • stringfield4

表2

  • ID
  • table1_id
  • stringfield1
  • datefield1

鉴于 UI 允许用户在以下位置进行fency查询:

  • dropdwonlist1,任何 table1.stringfield1
  • dropdwonlist2,任何 table1.stringfield2
  • dropdwonlist3,任何 table1.stringfield3
  • dropdwonlist4,任何 table1.stringfield4
  • dropdwonlist5,任何 table2.stringfield1
  • dropdwonlist6,[ any,the,before,after,between ]
  • calendar1与 table2.datefield1
  • 相关联
  • calendar2与 table2.datefield1
  • 相关联

结果datagridview with everyfields。

我想将条件查询构建为,如果不是“any”则添加此条件

考虑到这一点,简单的LINQ查询不适用:

Table2
  .Where(x => x.stringfield1 == dropdwonlist1.SelectedValue)
  .Where(x => x.stringfield2 == dropdwonlist2.SelectedValue)
  .Where(x => x.stringfield3 == dropdwonlist3.SelectedValue)
(...)

文档中有Expression trees,但看起来太多了。

是否有最简单的方法来构建我的动态查询?

3 个答案:

答案 0 :(得分:6)

表达式树看起来比它们更可怕,但你是对的,在你的情况下它们是不必要的:你可以使用一个足够智能的静态条件来忽略没有选择的下拉列表。你可以这样做:

Table2
.Where(x => dropdwonlist1.SelectedValue == null || x.stringfield1 == dropdwonlist1.SelectedValue)
.Where(x => dropdwonlist2.SelectedValue == null || x.stringfield2 == dropdwonlist2.SelectedValue)
.Where(x => dropdwonlist3.SelectedValue == null || x.stringfield3 == dropdwonlist3.SelectedValue)

答案 1 :(得分:2)

我已经将LINQKit用于类似场景并取得了巨大成功。

具体来说,您应该能够使用PredicateBuilder来完成您所寻找的目标。

答案 2 :(得分:1)

通常会忘记您可以在多个语句中继续构建LINQ表达式。这是LINQ的一大亮点。我将简化dasblinkenlight对LINQ-to-SQL转换的回答,该转换将在以后发生:

IQueryable<T> query = Table2;

if (dropdownlist1.SelectedValue == null)
    query = query.Where(x => x.stringfield1 == dropdownlist1.SelectedValue);
// etc

这样,任何具有null值的东西都不会混淆到where子句中,从而减少了生成的SQL在其中存在不必要条件的可能性。

我最喜欢Donut的答案作为一个更通用的解决方案 - 例如LINQKit会让你在6个下拉列表上写一个循环,如果有必要的话写下每个where子句。