Search function with unknown indata
I'd like to make a search function that takes indata from 5 textboxes, Name, gender,ID, animal category and animal. The diffrances between animal category and animal is for eg. animal category = mammal and animal = bear. So these are optional to the user, when he/she hits the button it should search for the given parameters. The data is saved in an genereic list with the Animal type. eg. ListanimalCollection
I tried to use linq, my query ->
ienumerable<Animal> result=
from a in animalCollection where a.Name== myParameterName
&&
a.Gender == myParameterGender
select a;
the problem comes to when user wants to have one or more than two parameters cu开发者_开发问答s i don't know how to make the query depending on user input. Do i have to make a bunch of if-statements to check user input? I hope there is another way!
Im asking you smart experts for help with this! Hope i made myself clear enough.
Daniel, sweden
Assuming that your parameters are all strings then you could do something like this:
var result = from a in animalCollection
where (string.IsNullOrEmpty(myParameterName) || a.Name == myParameterName)
&& (string.IsNullOrEmpty(myParameterGender) || a.Gender == myParameterGender)
&& (string.IsNullOrEmpty(myParameterID) || a.ID == myParameterID)
&& (string.IsNullOrEmpty(myParameterCategory) || a.Category == myParameterCategory)
&& (string.IsNullOrEmpty(myParameterAnimal) || a.Animal == myParameterAnimal)
select a;
精彩评论