How to

dynamically add generic condition to IQueryable

Published: 14. February 2012 | Updated: 14. February 2012
License: Microsoft Public License (MS-PL)
Categories: Collections » Linq
Tags: C# Collections Linq
Was this snippet helpful for you? YESYES / NONO

Import namespaces

using System;
using System.Linq;
using System.Linq.Expressions;

Method

public static class Extensions
{
    public static IQueryable<T> AddEqualityCondition<T, V>(this IQueryable<T> queryable, string propertyName, V propertyValue)
    {
        ParameterExpression pe = Expression.Parameter(typeof(T), "p");

        IQueryable<T> x = queryable.Where<T>(
            Expression.Lambda<Func<T, bool>>(
            Expression.Equal(Expression.Property(pe, typeof(T).GetProperty(propertyName)),
                Expression.Constant(propertyValue, typeof(V)), false, typeof(T).GetMethod("op_Equality")), new ParameterExpression[] { pe }));

        return (x);
    }
}

Use

IQueryable<MyClass> queryable = ... // get data

queryable = queryable.AddEqualityCondition("Text", "abc");
queryable = queryable.AddEqualityCondition("Value", 5);
Send us feedback about this snippet »



Related Snippets: