Conditional Linq Queries
I have a dropdownlist which when selected pulls the data out of a database. There are many options in the dropdownlist and one of them is "All". I want that when the user selects the "All" option it should pull everything out of the database开发者_JAVA技巧. What is a good way to implement this feature?
With LINQ you can easily modify a query before you send it to the database:
IQueryable<Item> query = dataContext.Items;
if (selectedText != "All")
{
query = query.Where(item => item.Type == selectedText);
}
List<Item> result = query.ToList();
Alternatively you can write it in a single query:
IQueryable<Item> query = dataContext.Items
.Where(item => selectedText == "All" || item.Type == selectedText);
Check the value, and only perform the Where statement if not "All".
var linqQuery = ...
if (selectedValue != "All")
linqQuery = linqQuery.Where(w => w.Value == selectedValue);
If you are dynamically building your queries a lot, then you might want to have a look at one of the really cool Linq samples, "the Dynamic Linq library". Scott Guthrie has a nice blog post about it.
Edit: Note in this specific case because you are on the right side of the where clause, you don't need to be completely dynamic and this would be overkill, but if you have a situation where you are also filtering dynamically, then.....
精彩评论