Aug 18, 2009

Multiple filters in LINQ

It all started with a need to have multiple filter parameters in a LINQ query. I didn't want to cascade results from one filter to another.

Following describes the approach to build multiple, dynamic, conditional filters into a LINQ query.
The approach uses LINQKIT to achieve this.

Problem definition:
I have a questions table with columns questionid, question, questiontype, questionrating etc. And, i would like to filter based on questiontype and questionrating. Also, i would like to choose either or none of the filters dynamically while executing the LINQ query. My front end UI has two drop downs one each for questiontype and questionrating. I may choose to apply or ignore one or more of the filters during run time.

One way to achieve this would be using Expression trees in Entity framework. Another easier approach(explained below) would be to use the LINQKIT and PredicateBuilder.

Solution:
Given the above problem definition, i have used LINQKIT and PredicateBuilder to easily solve the problem. I have used OR condition filter in my sample below.

var conditions = PredicateBuilder.False();

//check the applicability of filters
IDictionary filterDict = new Dictionary();
long temp = 0;

if (filter.QuestionType != questionTypeEnum.none)
{
temp = (long)filter.QuestionType;
conditions = conditions.Or(e => e.Qbank_type.typeIdInt == temp);
}
if (filter.QuestionRating != questionRatingEnum.none)
{
temp = (long)filter.QuestionRating;
conditions = conditions.Or(e => e.Qbank_questionRating.ratingIdInt == temp);
}

questionsResult = objectContext.questionsSet.AsExpandable().Where(conditions).OrderBy(e => e.questionId);
Related articles for an interesting read.
PredicateBuilder
LINQKIT (includes PredicateBuilder)

Reblog this post [with Zemanta]

No comments:

Post a Comment