有一些選擇這裏:
- 您可以使用
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()
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
條件是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();
你可以使用規範模式 –