-10

我的 LINQ 查询类似于下面的代码。

 var data2 = data.Where(c => String.Format("{0:MM/dd/yyyy}", c.OrderDate) == "07/04/1996");

我需要在下面的表达式中自定义格式化列的谓词。我需要为谓词编写表达式并根据格式过滤数据。请检查下面的代码。

pred =Expression.Equal(membertype, Expression.Constant(value, type));
lambda = Expression.Lambda(predicate, paramExpression);
source.Where(paramExpression, predicate);

谢谢。

4

1 回答 1

0

.Where这是一个动态创建的示例。

static void DynamicWhereBuilder() {
  var datas = new Data[] {
    new Data { OrderDate  = "07/04/1996"},
    new Data { OrderDate  = "07/04/1990"},
    new Data { OrderDate  = "07/04/2001"},
    new Data { OrderDate  = "2012/04/07"}
  };
  IQueryable<Data> queryableData = datas.AsQueryable<Data>();

  var formatConstant = Expression.Constant("{0:MM/dd/yyyy}", typeof(string));
  var parameter = Expression.Parameter(typeof(Data), "dataArg");
  var property = Expression.Property(parameter, "OrderDate");

  var left = Expression.Call(property, typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object) }), formatConstant, property);
  var right = Expression.Constant("07/04/2001", typeof(string));

  var equal = Expression.Equal(left, right);
  var whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { queryableData.ElementType },
    queryableData.Expression,
    Expression.Lambda<Func<Data, bool>>(equal, new ParameterExpression[] { parameter }));
  var results = queryableData.Provider.CreateQuery<Data>(whereCallExpression); // returns the object with OrderDate = "07/04/2001"
}
于 2012-07-12T10:34:33.577 回答