LINQ:具有通用 属性 和值的动态 where

LINQ: Dynamic where with generic property and value

我正在尝试构建一个简单的 select 方法,用于通过通用静态方法查询 Linq-to-SQL table。我坚持动态创建表达式。

这里有同样的问题:LINQ : Dynamic select

F.ex Select 所有姓名为 "Jack" = Person.Name = "Jack"[=13 的人=]

public static List<T> selectBy<T,P>(String column, P value) where T : class {
    try {
        // First resolve the used table according to given type
        Table<T> table = database.GetTable<T>();

        // Get the property according to given column
        PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column);

        //Func<Data,Data> expressionHere

        // Select all items that match the given expression
        List<T> objectList = table.Where(expressionHere).ToList<T>();

        // Return the filled list of found objects
        return objectList;

    } catch (Exception ex) {
        Debug.WriteLine("selectBy", ex.Message.ToString());
        return null;
    }
}

您可以像这样手动构造表达式:

// First resolve the used table according to given type
Table<T> table = database.GetTable<T>();

// Get the property according to given column
PropertyInfo property = typeof(T).GetTypeInfo().GetDeclaredProperty(column);

//Func<Data,Data> expressionHere
ParameterExpression lambdaArg = Expression.Parameter(typeof(T));
Expression propertyAccess = Expression.MakeMemberAccess(lambdaArg, property);
Expression propertyEquals = Expression.Equal(propertyAccess, Expression.Constant(value, typeof(P)));
Expression<Func<T, bool>> expressionHere = Expression.Lambda<Func<T, bool>>(propertyEquals, lambdaArg);

// Select all items that match the given expression
List<T> objectList = table.Where(expressionHere).ToList<T>();

// Return the filled list of found objects
return objectList;