Tuesday 24 March 2015

Linq - Dynamically add new Where clauses to existing query depending on conditions

Create the following new extensions which would be hooked to our existing linq methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace CommonClass
{
    public static class Extensions
    {
        public static IQueryable WhereIf(this IQueryable source, bool condition, Expression> predicate)
        {
            if (condition)
                return source.Where(predicate);
            else
                return source;
        }

        public static IEnumerable WhereIf(this IEnumerable source, bool condition, Func predicate)
        {
            if (condition)
                return source.Where(predicate);
            else
                return source;
        }
    }
}

Now we can use the above extensions to add where clauses to existing query as follows:

var x = "Test";
var y = 5;
var z = ""US; 
var query = dbContext.tblSample
                    .Where(b => b.sampleId == y)
                    .WhereIf(x.Equals(b.Name), p => p.Country.Equals(z));
var result = query.Select(s => s.ColumnName);