2012-04-30 136 views
1
lstReport=lstReport.Where(o=>DateTime.Parse(o.Field)==DateTime.Parse(o.FieldValue)); 
//I am creating above statement dynamically like this 
var variable = Expression.Variable(typeof(Report)); 
foreach (SQWFilterConstraint oFC in oFilter.LstFilterConstraint) //using this collection I am making dynamic query 
{ 
    Expression ExprLeft =Expression.Property(variable, oFC.Field); 
    MethodInfo methodDateTimeParse = typeof(DateTime).GetMethod("Parse", newType[] { typeof(string) }); 
    var methodParam = Expression.Parameter(typeof(string), oFC.FieldValue); 
    Expression exprRight = Expression.Call(methodDateTimeParse, methodParam); //This is working fine for right side 
} 
var props = new[] { variable }; 
var lambda = Expression.Lambda<Func<Report, bool>>(ExprPrev, props).Compile(); 
ReportList = ReportList.Where(lambda).ToList(); 

所以我需要應用領域上也DateTime.Parse方法,正值左側(這是下劃線和粗體以上運營商的左側)如何在創建表達式樹時使用DateTime.Parse()方法(即在表達式左側和表達式右側)?

+0

你爲什麼不做同樣的事情你已經做的右側? – svick

+0

我試過,但它不工作,因爲我不提供參數var methodParam = Expression.Parameter(typeof(string),oFC.FieldName); //此函數期望常量值作爲第二個參數而不是fieldname –

回答

0

不知道你想達到的目標。

1)什麼是foreach?每個屬性都必須進行比較?

2)ExprPrev從未被聲明過。

無論如何,創建表達式的方式如下。

[TestMethod] 
     public void TestDateTimeParse() 
     { 
      var variable = Expression.Variable(typeof (Report)); 

      var parseMethodInfo = typeof (DateTime).GetMethod("Parse", new[] {typeof (string)}); 
      var left = Expression.Call(parseMethodInfo, Expression.Property(variable, "Field")); 
      var right = Expression.Call(parseMethodInfo, Expression.Property(variable, "FieldValue")); 
      var equals = Expression.Equal(left, right); 

      var expression = Expression.Lambda<Func<Report, bool>>(equals, variable).Compile(); 

      var target = new Report {Field = DateTime.Now.ToString()}; 
      target.FieldValue = target.Field; 
      expression(target).Should().Be.True(); 
     } 

     public class Report 
     { 
      public string Field { get; set; } 
      public string FieldValue { get; set; } 
     }