Dynamic Where for List

前端 未结 3 1678
别跟我提以往
别跟我提以往 2020-12-30 14:37

I\'m trying to create a dynamic filter for various classes. We would only know at runtime what type we\'re dealing with. I need the ColumnName to be the actual column (not

3条回答
  •  一个人的身影
    2020-12-30 15:02

    Basically you need to build an expression tree. It's not terribly hard, fortunately, using Expression.Property. You can either pass that to Queryable.Where, or compile it and pass it to Enumerable.Where. (Obviously you'll need to use something like Expression.Equal as well, depending on the type of comparison you're trying to make.)

    Is CompValue meant to be an actual value? What's TypeOfCompare meant to be?

    I'm not sure where LINQ to Entities fits into this, either... you're only using LINQ to Objects really, as far as I can see.

    EDIT: Okay, here's a sample. It assumes you want equality, but it does what you want if so. I don't know what the performance impact of compiling an expression tree every time is - you may want to cache the delegate for any given name/value combination:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    
    static class Extensions
    {
        public static List Filter
            (this List source, string columnName, 
             string compValue)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
            Expression property = Expression.Property(parameter, columnName);
            Expression constant = Expression.Constant(compValue);
            Expression equality = Expression.Equal(property, constant);
            Expression> predicate =
                Expression.Lambda>(equality, parameter);
    
            Func compiled = predicate.Compile();
            return source.Where(compiled).ToList();
        }
    }
    
    class Test
    {
        static void Main()
        {
            var people = new[] {
                new { FirstName = "John", LastName = "Smith" },
                new { FirstName = "John", LastName = "Noakes" },
                new { FirstName = "Linda", LastName = "Smith" },
                new { FirstName = "Richard", LastName = "Smith" },
                new { FirstName = "Richard", LastName = "Littlejohn" },
            }.ToList();
    
            foreach (var person in people.Filter("LastName", "Smith"))
            {
                Console.WriteLine(person);
            }
        }
    }
    

提交回复
热议问题