基本上,您需要构建一个表达式树。幸运的是,使用
Expression.Property
并不难。您可以将其传递给
Queryable.Where
,也可以编译它并将其传递给
Enumerable.Where
。(显然,您还需要使用类似于
Expression.Equal
的东西,具体取决于您要进行的比较类型。)
< p >
CompValue
是否表示实际值?
TypeOfCompare
表示什么?
我也不确定LINQ to Entities在这里扮演了什么角色...就我所看到的,您只是在使用LINQ to Objects。
编辑:好吧,这里有一个示例。它假定您想要相等性,但如果是这样,它会做您想要的事情。我不知道每次编译表达式树的性能影响如何-您可能需要为任何给定的名称/值组合缓存委托:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
static class Extensions
{
public static List<T> Filter<T>
(this List<T> 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<Func<T, bool>> predicate =
Expression.Lambda<Func<T, bool>>(equality, parameter);
Func<T, bool> 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);
}
}
}