Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Expression<Func<IBar, T>> to Expression<Func<Bar, T>>

Tags:

c#

lambda

linq

How do you convert from Expression<Func<IBar, T>> to Expression<Func<Bar, T>> when Bar implements IBar?

There is the answer to this more generic question:

Convert Expression<Func<T1,bool>> to Expression<Func<T2,bool> dynamically

Is that the best method in this case? Is there not an easier way given that Bar implements IBar?

So, given this contrived example code:

          public class Foo<T>
          {
                 private readonly List<T> _list = new List<T>();

                 public void Add(T item)
                 {
                       _list.Add(item);
                 }

                 public bool AnyFunc(Func<T, bool> predicate)
                 {
                       return _list.Any(predicate);
                 }

                 public bool AnyExpression(Expression<Func<T, bool>> expression)
                 {
                       return _list.AsQueryable().Any(expression);
                 }                    
          }

          public interface IBar
          {
                 string Name { get; }
          }

          public class Bar : IBar
          {
                 public string Name { get; set; }
          }

This demonstrates the problem:

          public class Test()
          {
                 private Foo<Bar> _foobar = new Foo<Bar>(); 

                 public void SomeMethodFunc(Func<IBar, bool> predicate)
                 {
                       // WILL COMPILE AND WORKS, casts from Func<IBar, bool> to Func<Bar, bool>
                       var found = _foobar.AnyFunc(predicate);
                 }

                 public void SomeMethodExpression(Expression<Func<IBar, bool>> expression)
                 {
                       // WON'T COMPILE - Can't cast from Expression<Func<IBar, bool>> to Expression<Func<Bar, bool>>  
                       var found = _foobar.AnyExpression(expression);
                 }
          }

Any ideas how I can accomplish something similar to SomeMethodExpression?

like image 462
tikinoa Avatar asked Mar 05 '26 12:03

tikinoa


1 Answers

Since this case is simple and related to "casting" issues only, there is a shortcut:

public void SomeMethodExpression(Expression<Func<IBar, bool>> expression)
{
    Expression<Func<Bar, bool>> lambda = Expression.Lambda<Func<Bar, bool>>(expression.Body, expression.Parameters);
    var found = _foobar.AnyExpression(lambda);
}
like image 93
Amir Popovich Avatar answered Mar 07 '26 06:03

Amir Popovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!