2017-05-21 21 views
0

我在我的列表中使用多個篩選器項目。如何正確地跳過一些塊,如果有些過濾器字段是空的?如何跳過一些條件時使用多個在LINQ

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

有一些選擇這裏:

  • 您可以使用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();
+0

謝謝。只有一個備註:如果未選擇任何值,ComboBox.SelectedIndex返回-1,而不是null。 – Wuzaza

+0

@Wuzaza:謝謝。改性。不知何故,我忘記了(這可能是同時使用各種語言的效果:S) –

0

您可以在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(); 
相關問題