簡體   English   中英

轉換謂詞 <T> 表達 <Func<T, bool> &gt;

[英]Convert Predicate<T> to Expression<Func<T, bool>>

是否可以以某種方式將Predicate<T> to Expression<Func<T, bool>>轉換Predicate<T> to Expression<Func<T, bool>>

我想使用我的ICollectionView的過濾器使用下一個IQueryable函數:

public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate)

謝謝

像這樣的東西?

Predicate<string> predicate = input => input.Length > 0;
Expression<Func<string, bool>> expression = (input) => predicate(input);

你可以創建一個擴展, Where ICollectionView的方法接受一個謂詞,將它轉換為這樣的表達式,然后調用Linq提供的Where方法。

public static IQueryable<T> Where(this IQueryable<T> source, Predicate<T> predicate)
{
    return source.Where(x => predicate(x));
}

從理論上講,可以將委托“后退”轉換為表達式,因為您可以請求委托的發出IL,從而為您提供轉換它所需的信息。

但是,這是因為LINQ to SQL和Entity Framework都沒有這樣做。 這樣做復雜,脆弱且性能密集。

所以簡短的回答是,你無法將其轉換為表達式。

namespace ConsoleApplication1
{
    static class Extensions
    {
        public static Expression<Func<T, bool>> ToExpression<T>(this Predicate<T> p)
        {
            ParameterExpression p0 = Expression.Parameter(typeof(T));
            return Expression.Lambda<Func<T, bool>>(Expression.Call(p.Method, p0), 
                  new ParameterExpression[] { p0 });
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM