Miguel Moura
Miguel Moura

Reputation: 39514

Dynamic where condition in query

I have the following:

IQueryable<Post> posts = _context.Posts;
String rank = "1";
posts = posts.Where(x => x.Rank == rank);

I would like to create a Where extension in order to use it like this:

posts = posts.Where(x => x.Rank, rank);

Which would translate into posts.Where(x => x.Rank == rank).

I am passing the property to be applied (x.Rank) and the rule (rank)

The reason why I am using this is because rank rule could be:

[minRank;maxRank], [;maxRank], [minRank;], etc.

So I will build the query based on a set of rules. For example:

// [minRank;maxRank]:
posts = posts.Where(x => x.Rank >= minRank && x.Rank <= maxRank);

// [;maxRank]:
posts = posts.Where(x => x.Rank <= maxRank);    

There will be more rules that I will plan to add.

The steps I am considering to build the query would be:
1. Parse the rule info;
2. Check which rule type is (equals, range, ...)
3. Check the type of x.Rank
4. Create the Where query for that rule with that property.

Upvotes: 0

Views: 65

Answers (1)

Slava Utesinov
Slava Utesinov

Reputation: 13498

What about this:

public static class Extentions
{
    public static IQueryable<T> Where<T, P>(this IQueryable<T> self, Func<T, P> selector, P value) 
        where P : IComparable
    {
        return self.Where(x => selector(x).CompareTo(value) >= 0);
    }
}

Upvotes: 1

Related Questions