Search code examples
c#expression-trees

Would this be the correct usage of an expression tree?


I've these two similar methods and I feel they can be replaced with an expression tree passing in the greater than or less than signs

public List<IAccount> IsGreater(DateTime someDate)
{    
    return AccountList.Where(a => 
           a.AccountDate >= someDate && a.SomeBoolMethod() && a.SomeOtherBoolMethod()) 
}

public List<IAccount> IsLess(DateTime someDate)
{    
    return AccountList.Where(a => 
           a.AccountDate < someDate && a.SomeBoolMethod() && a.SomeOtherBoolMethod())   
}

From what I've read about expression trees I feel something like this could be in order

 Expression<Func<DateTime, ExpressionType, DateTime, bool, bool, bool, List<IAccount>>> 
      expression = (a, b, c, d, e, f) =>
      {
          // not sure how to do this here
      }

Am I in the right neighborhood?


Solution

  • Why build an entire expression tree? As the question is currently stated, you can just pass in the comparison.

    public List<IAccount> FilterAccounts( Predicate<IAccount> condition )
    {    
        return AccountList.Where(a => condition(a) && a.SomeBoolMethod() && a.SomeOtherBoolMethod() )
    }
    
    public List<IAccount> IsGreater(DateTime someDate)
    {    
        return FilterAccounts( a => a.AccountDate >= someDate );
    }
    
    public List<IAccount> IsLess(DateTime someDate)
    {    
        return FilterAccounts( a => a.AccountDate < someDate );
    }