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

时间:2017-05-21 17:21:35

标签: c# linq 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();

2 个答案:

答案 0 :(得分:0)

这里有一些选择:

  • 您可以使用procedure TForm.btnCMDLaunchClick(Sender: TObject); var commandLine: string; si: TStartupInfo; pi: TProcessInformation; begin commandLine := Format('%s %s',['C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe', 'F:\Android-interview\Packt.Android.3.0.Application.Development.Cookbook.Jul.2011.ISBN.1849512949.pdf']); UniqueString(commandLine); si := Default(TStartupInfo); si.cb := sizeof(si); if CreateProcess( PChar(nil), //no module name (use command line) PChar(commandLine), //Command Line nil, //Process handle not inheritable nil, //Thread handle not inheritable False, //Don't inherit handles 0, //No creation flags nil, //Use parent's environment block PChar(nil), //Use parent's starting directory si, //Startup Info pi //Process Info ) then begin CloseHandle(pi.hProcess); CloseHandle(pi.hThread); end; end; 并仅有条件地添加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

答案 1 :(得分:0)

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

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