Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Filter Implementation with Expressions

Tags:

c#

linq

In MVC4 , I am providing Search box to the user to search any value in Table. So I am implementing Generic Filter Condition at server side in C#

Need a help to combine multiple expressions to form single expression

 Expression<Func<T, bool>> 

For Example

Table Columns

MenuText, Role Name (Role.Name mapping), ActionName

Now If user entered in search box for ABC , which can be in any of the rows in shown columns, need to filter.

Model

public class Menu
{
  public string MenuText {get;set;}
  public Role Role {get;set;}
  public string ActionName {get;set;}
}

public class Role
{
  public string Name {get;set;}
}

So far I have implemented

  /// <summary>
    /// string[] properties property.Name (MenuText, ActionName), including deeper Mapping names such as (Role.Name)
    /// </summary>
    public static Expression<Func<T, bool>> FilterKey<T>(string filterText, params string[] properties)
    {
        ParameterExpression parameter = Expression.Parameter(typeof (T));
        Expression[] propertyExpressions = properties.Select(
            x => !string.IsNullOrEmpty(x) ? GetDeepPropertyExpression(parameter, x) : null).ToArray();

        Expression<Func<T, bool>> predicate = PredicateBuilder.False<T>();
        foreach (Expression expression in propertyExpressions)
        {
             var toLower = Expression.Call(expression, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
            var like = Expression.Call(toLower, typeof(string).GetMethod("Contains"), Expression.Constant(filterText.ToLower()));
            //TODO: Combine expressions to form single  Expression<Func<T, bool>> expression

        }
        return predicate;
    }

       /// <summary>
        ///  To Get Deeper Properties such as Role.Name Expressions
        /// </summary>
       private static Expression GetDeepPropertyExpression(Expression initialInstance, string property)
        {
            Expression result = null;
            foreach (string propertyName in property.Split('.'))
            {
                Expression instance = result ?? initialInstance;
                result = Expression.Property(instance, propertyName);
            }
            return result;
        }
like image 758
ineffable p Avatar asked Jul 25 '13 10:07

ineffable p


1 Answers

I have created a few search IQueryable extension methods that you should be able to use

Full blog post is here:

http://jnye.co/Posts/6/c%23-generic-search-extension-method-for-iqueryable

GitHub project is here (has a couple of extra extensions for OR searches:

https://github.com/ninjanye/SearchExtensions

public static class QueryableExtensions  
{  
    public static IQueryable<T> Search<T>(this IQueryable<T> source, Expression<Func<T, string>> stringProperty, string searchTerm)  
    {  
        if (String.IsNullOrEmpty(searchTerm))  
        {  
            return source;  
        }  

        // The below represents the following lamda:  
        // source.Where(x => x.[property] != null  
        //                && x.[property].Contains(searchTerm))  

        //Create expression to represent x.[property] != null  
        var isNotNullExpression = Expression.NotEqual(stringProperty.Body, Expression.Constant(null));  

        //Create expression to represent x.[property].Contains(searchTerm)  
        var searchTermExpression = Expression.Constant(searchTerm);  
        var checkContainsExpression = Expression.Call(stringProperty.Body, typeof(string).GetMethod("Contains"), searchTermExpression);  

        //Join not null and contains expressions  
        var notNullAndContainsExpression = Expression.AndAlso(isNotNullExpression, checkContainsExpression);  

        var methodCallExpression = Expression.Call(typeof(Queryable),  
                                                   "Where",  
                                                   new Type[] { source.ElementType },  
                                                   source.Expression,  
                                                   Expression.Lambda<Func<T, bool>>(notNullAndContainsExpression, stringProperty.Parameters));  

        return source.Provider.CreateQuery<T>(methodCallExpression);  
    }  
}  

This allows you to write something like:

string searchTerm = "test";  
var results = context.Menu.Search(menu => menu.MenuText, searchTerm).ToList();  

//OR for Role name
string searchTerm = "test";
var results = context.Menu.Search(menu => menu.Role.Name, searchTerm).ToList();

You might also find the following posts useful:

Search extension method that allows search accros multiple properties:

http://jnye.co/Posts/7/generic-iqueryable-or-search-on-multiple-properties-using-expression-trees

Search extension method that allows multiple or search terms on a property:

http://jnye.co/Posts/8/generic-iqueryable-or-search-for-multiple-search-terms-using-expression-trees

like image 70
NinjaNye Avatar answered Sep 25 '22 00:09

NinjaNye