Reputation: 12809
I have a Dropdownlist with options 'dog', 'cat' and 'all'.
If this just had 'dog' or 'cat' there would be no issue I could just write ...
var SelectedPets = pets.Where(x => w.species == ViewModel.SlectedDropdownListSpecies)
My application has several of these Dropdownlists with several choices + 'all'.
The only way i can see to implement the all option in Linq is with a series of if statements - if the user selects 'all' then the Where is just not used at all.
I'm looking to avoid this kind of code:
if (ViewModel.SelectedDropdownListSpecies != 'all')
{
SelectedPets = Pets.Where(x => w.species == ViewModel.SlectedDropdownlistValue)
}
if (ViewModel.SelectedDropdownlistValue2 != 'all')
{
SelectedPets = SelectedPets.Where(x => w.colour == ViewModel.SlectedDropdownListColour)
}
Is there a way that I can have a Linq expression similar to the above that also somehow honours the 'all' value.
It's a greenfield app so I have a lot of wiggle room in terms of how this is implemented.
I haven't been able to find anything on Google - not really sure what to search for exactly. Thanks.
Upvotes: 0
Views: 38
Reputation: 1016
Perhaps:
var SelectedPets = pets.Where(x => w.species == ViewModel.SlectedDropdownlistValue || ViewModel.SlectedDropdownlistValue == "all")
Upvotes: 3