我在列表中使用多个过滤器项目。如果某些过滤字段为空,如何正确跳过某些块?
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();
答案 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();