Chuy Naranjo
Chuy Naranjo

Reputation: 11

dynamic filters in asp.net mvc 4

I want to do something like this:

var list = db.Respaldoes.Where(x => x.type == "Backup");

if (condicion1)
    list.Where(x => x.entity == "GIELCJLT03");

if (condicion2)
    list.Where(x => x.activity_type == "0");

I don't know if something like this is possible, I get the list but the filters are never applied.

Upvotes: 0

Views: 811

Answers (2)

David L
David L

Reputation: 33815

Where returns an IEnumerable<T>, which defers the execution until a later action forces the query to be resolved. If you want to resolve your query, immediately execute it with ToList().

In addition, you are not actually doing anything with your filtered list. By reassigning the filtered list to your original list object, it will update the collection with the filter, removing objects that do not match your predicate.

var list = db.Respaldoes.Where(x => x.type == "Backup");

if (condicion1)
    list = list.Where(x => x.entity == "GIELCJLT03").ToList();

if (condicion2)
    list = list.Where(x => x.activity_type == "0").ToList();

Upvotes: 1

Christos
Christos

Reputation: 53958

You could try something like this:

var list = db.Respaldoes.Where(x => x.type == "Backup");

if (condicion1)
    list = list.Where(x => x.entity == "GIELCJLT03");

if (condicion2)
    list = list.Where(x => x.activity_type == "0");

Initially the list when the Where clause, x => x.type == "Backup", will be executed it will give you the initial list you refer to. Then, if the condicion1 is true, you will make a second fitering and you will assign the result to list. There again you have deffered execution. Only when list will be requested to be consumed by another piece of your code will be executed -hence the name deffered execution. The same holds for the second condicion and so on.

Upvotes: 1

Related Questions