Reputation: 129
I am trying to convert from
x => x.SomeProperty
to
x => x.SomeProperty is ISomeInterface
In a method that fits the following signature:
Func<TSource, bool> Convert(Expression<Func<TSource, TSourceMember>> source);
Where SomeProperty might be a collection or a single object. Can anyone help?
I'm finding it difficult to work out what kind of expressions these are. I think that the first one is a MemberExpression and the second is a UnaryExpression.
I'd be happy to move the
x.SomeProperty is ISomeInterface
logic into a method if that would make things easier.
bool IsSomeInterface(object obj)
{
return obj is ISomeInterface;
}
Any pointers or tutorials on how to put this stuff together would be appreciated. I always seem to struggle with Expression trees.
Upvotes: 1
Views: 201
Reputation: 1341
You might be looking for Expression.TypeIs(...)
. Try this:
Func<TSource, bool> Convert<TSource, TSourceMember>(Expression<Func<TSource, TSourceMember>> source)
{
return (Func<TSource, bool>)(Expression.Lambda<Func<TSource, bool>>(Expression.TypeIs(source.Body, typeof(ISomeInterface)), source.Parameters).Compile());
}
Upvotes: 3