简体   繁体   English

在Linq中使用多个where时如何跳过某些条件

[英]How to skip some conditions when using multiple where in linq

I'm using multiple where filter items in my list. 我在列表中使用了多个where过滤器项。 How to properly skip some where blocks, if some filter fields are empty? 如果某些过滤器字段为空,如何正确跳过一些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();

There are some options here: 这里有一些选项:

  • you can use an if and only conditionally add a Where clause; 您可以使用if并且仅有条件地添加Where子句; or 要么
  • you can use logic such that the filter is true if the filter field is empty. 您可以使用逻辑,如果过滤器字段为空,则过滤器为true

The first one can be resolved like: 第一个可以像下面这样解决:

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

The latter can be solved as follows: you change the filter: 后者可以按以下方式解决:更改过滤器:

s => some_condition

to: 至:

s => filter_field_is_empty || some_condition

Such that if the filter_field_is_empty condition is true , it will thus let the element pass in the filter. 这样,如果filter_field_is_empty条件为true ,那么它将使元素通过过滤器。 Note that this will usually be less efficient because the test is done for every element : 请注意,这通常效率较低,因为对每个元素都进行了测试:

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

You can use string.IsNullOrWhiteSpace in the Where clause. 您可以在Where子句中使用string.IsNullOrWhiteSpace Here is the code: 这是代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM