【问题标题】:How to skip some conditions when using multiple where in linq在linq中使用多个where时如何跳过某些条件
【发布时间】:2017-05-21 17:21:35
【问题描述】:

我在列表中使用了多个 where 过滤器项目。如果某些过滤器字段为空,如何正确跳过某些 where 块?

IEnumerable<MyNewClass> filterResult = itemList.Where(s => s.name == nameFilterTextBox.Text)
                                                       .Where(s => s.description == descriptionFilterTextBox.Text)
                                                       .Where(s => s.color == (MyNewClass.Colors)comboBox1.SelectedIndex).ToList();

【问题讨论】:

  • 你可以使用规范模式

标签: c# linq where


【解决方案1】:

您可以在Where 子句中使用string.IsNullOrWhiteSpace。代码如下:

IEnumerable<MyNewClass> filterResult = 
    itemList.Where(s =>
      (string.IsNullOrWhiteSpace(nameFilterTextBox.Text) || s.name == nameFilterTextBox.Text) &&
      (string.IsNullOrWhiteSpace(descriptionFilterTextBox.Text) || s.description == descriptionFilterTextBox.Text) &&
      s.color == (MyNewClass.Colors)comboBox1.SelectedIndex).ToList(); 

【讨论】:

    【解决方案2】:

    这里有一些选项:

    • 您可以使用if,并且只能有条件地添加Where 子句;或
    • 如果过滤器字段为空,您可以使用过滤器为true 的逻辑。

    第一个可以这样解决:

    IEnumerable<MyNewClass> filterResult = itemList;
    if(nameFilterTextBox.Text != "") {
        filterResult = filterResult.Where(s => s.name == nameFilterTextBox.Text);
    } if(descriptionFilterTextBox.Text != "") {
        filterResult = filterResult.Where(s => s.description == descriptionFilterTextBox.Text)
    } if(comboBox1.SelectedIndex != -1) {
        MyNewClass.Colors col = (MyNewClass.Colors)comboBox1.SelectedIndex;
        filterResult = filterResult.Where(s => s.color == col);
    }
    // do something with filterResult.ToList()

    后者可以这样解决:你换个过滤器:

    s => some_condition
    

    到:

    s => filter_field_is_empty || some_condition
    

    这样,如果filter_field_is_empty 条件是true,它将因此让元素通过过滤器。请注意,这通常效率较低,因为测试是针对每个元素完成的:

    IEnumerable<MyNewClass> filterResult = itemList
        .Where(s => nameFilterTextBox.Text == "" || s.name == nameFilterTextBox.Text)
        .Where(s => descriptionFilterTextBox.Text == "" || s.description == descriptionFilterTextBox.Text)
        .Where(s => comboBox1.SelectedIndex == -1 || s.color == (MyNewClass.Colors)comboBox1.SelectedIndex).ToList();

    【讨论】:

    • 谢谢。只有一句话:ComboBox.SelectedIndex 如果没有选择值,则返回 -1,而不是 null。
    • @Wuzaza:谢谢。修改的。不知何故我忘记了(这可能是同时使用各种语言的效果:S)
    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多