I would like to select data from database according to what the user has entered. However, if that condition is not provided (null), it will ignore that condition and only take the provided conditions to filter out the relevant rows.
I find my solution (pseudocode) to be very inefficient and ugly and I hope someone can share his/her knowledge with me.
This is what I have tried:
'''
//selectConditions - input by user
var dataList = from data in entities.StudentsData
orderby data.Id
select data;
if (selectCondition.Age != null)
{
dataList = filter(dataList, selectCondition.Age);
}
if (selectCondition.Gender != null)
{
dataList = filter(dataList, selectCondition.Gender);
}
//may contain more conditions
//dataList now contains all rows with conditions specified by user
'''
So If I have a table
Name Age Gender
Tom 12 Male
Mary 13 Female
May 15 Female
Jack 14 Male
Case 1: Conditions are
Gender: Male
Age: null
I should get
Tom 12 Male
Jack 14 Male
Case 2: Conditions are
Gender: Female
Age: 15
I should get
May 15 Female