tags:

views:

49

answers:

3

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. What is a good way to implement this feature?

+1  A: 

Check the value, and only perform the Where statement if not "All".

var linqQuery = ...
if (selectedValue != "All")
    linqQuery = linqQuery.Where(w => w.Value == selectedValue);
Andrew Koester
+7  A: 

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);
Mark Byers
or maybe: query.Where(item => selectedText == "All" || item.Type == selectedText);
mgroves
@mgroves: Thanks, added.
Mark Byers
A: 

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.....

Tim Jarvis