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

时间:2015-03-24 13:54:09

标签: c# linq generics linq-to-sql windows-phone-8.1

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

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

  • T 是数据库表(Person)的类
  • P 是值的类型。值和属性类型应该相同(F.ex String)
  • 是给定类的属性名称(“名称”)
  • value 是字段的where语句值(“Jack”)

F.ex选择姓名为“Jack”的所有人= Person.Name =“Jack”

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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

// 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;