How to filter IEnumerable based on an entity input parameter

前端 未结 3 1187
后悔当初
后悔当初 2021-01-01 01:31

I\'m using now Entity framework- but it\'s a problem \"shared\" between all ORM\'s and even IEnumerable.

Let\'s say I have a method in MVC looks like this:



        
3条回答
  •  情话喂你
    2021-01-01 01:53

    Try that. This is using reflection and expressions to build the query dynamically. I tested it only with objects.

    static IQueryable Filter(IQueryable col, T filter)
    {
        foreach (var pi in typeof(T).GetProperties())
        {
            if (pi.GetValue(filter) != null)
            {
                var param = Expression.Parameter(typeof(T), "t");
                var body = Expression.Equal(
                    Expression.PropertyOrField(param, pi.Name),
                    Expression.PropertyOrField(Expression.Constant(filter), pi.Name));
                var lambda = Expression.Lambda>(body, param);
                col = col.Where(lambda);
            }
        }
    
        return col;
    }
    

提交回复
热议问题