I need to create a custom “Contains” LINQ expression that derives from System.Linq.Expressions.Expression that internally performs an IEnumerable.Contains method call. This class will accept two expression parameters. The first evaluates to and instance of type IEnumerable collection and second evaluates to an instance of type T.
I need this to be its own class as i want to override the ToString method to return a custom string that represents the operation being performed.
So far, I have the following:
public class ContainsExpression : Expression
{
public ContainsExpression(Expression left, Expression right) :
base(ExpressionType.Call, typeof(ContainsExpression))
{
Left = left;
Right = right;
// Error here: value cannot be null
Expression.Call(
typeof(IEnumerable).GetMethod("Contains", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public), left, right);
}
public static ContainsExpression Contains(Expression itemExpr, Expression collectionExpr)
{
return new ContainsExpression(itemExpr, collectionExpr);
}
public override string ToString()
{
return Left.ToString() + " Contains " + Right.ToString();
}
public Expression Left { get; private set; }
public Expression Right { get; private set; }
}
I am having trouble with the Expression.Call. Basically, I want to invoke IEnumerable.Contains().
Any pointers is always appreciated. TIA.
Well, one problem is that the
IEnumerableinterface doesn’t have aContainsmethod. You’re probably looking for the extension-method declared inSystem.Linq.Enumerable.Try (assuming you have a
using System.Linq;directive):