I am building a search feature in an asp.net application and I am using LINQ to SQL to retrieve data based on the selected search criteria. The search criteria are
- Country
- City
- District
- number of rooms
- Rent Cycle
Only the first search criterion, Country, is the mandatory field. However, if the user entered values for criteria 2, 3, 4 and/or 5 then the entered values should be taken into account and only retrieve results that matched all entered search criterion. Notice that if one of the criterion 2, 3, 4 and/or 5 is left empty (null) then LINQ should act as ‘DONT CARE’ and return that row.
So for example, if the criteria entered are:
- Country = USA
- City = null
- District = null
- number of rooms = null
- Rent Cycle = null
Then all rows with Country == USA should be returned.
Another example:
- Country = UK
- City = null
- District = null
- number of rooms = 5
- Rent Cycle = null
Then all rows with Country == UK and NumberOfRooms == 5 should be returned.
How do I achieve this in LINQ to SQL?
Here is what i have so far:
var data = from x in db.Units where x.Country == coutnryID && /*PLEASE HELP!*/ select x;
Try this (assuming
cityId,districtId,roomsandrentCycleare the variables that you’re wanting to search on:I’m basically saying, if your variables you want to search on are null, then disregard them, otherwise match them to the corresponding field in the
Unit.