The Muffin Man
The Muffin Man

Reputation: 20004

Help with LINQ query and multiple client filters

I'm displaying a list of products and have 4 drop down lists to filter through this data.

How can I build a LINQ query that can take all of the other filters current values into consideration without having to write out every possible combination LINQ query for the filters?

I would like to choose a manufacture from the drop down, display those products and then be able to filter the new results by color and etc. Later I will hide filters that don't apply to new filtered results.

This website has exactly what I'm trying to do on the left side. The difference is I am filtering on autopostback(one filter at time).

Upvotes: 2

Views: 244

Answers (1)

Samuel Neff
Samuel Neff

Reputation: 74929

A LINQ query does not really have to be all one statement, you can build it in parts. When you create a LINQ query it doesn't actually do anything with the source data yet, it just builds up an expression of IEnumerable/IQueryable interfaces which build upon each other. As long as you don't execute it by enumerating it or calling a method like ToList(), then you can keep adding on to the query and it will not get executed yet.

You want something like this:

// create original query, no filters
var query = from x in whatever....;

// add each filter one by one

if (condition1) 
{
    query = query.Where(row => condition 1 expression);
}

if (condition2)
{
    query = query.Where(row => condition 2 expression);
}

if (condition3)
{
    query = query.Where(row => condition 3 expression);
}   

if (condition4)
{
    query = query.Where(row => condition 4 expression);
}   

Upvotes: 2

Related Questions