簡體   English   中英

如何使用自定義擴展方法使用C#Linq謂詞

[英]How To Use C# Linq Predicate with custom Extension Method

我正在嘗試編寫一個C#擴展方法,它應該采用Predicate並返回IQueryable,這樣我就可以重用一個復雜的Where Predicate

這是我正在看的

    public static IEnumerable<T> AddComplexWhere<T>(this IEnumerable<T> query, DBContext context, Func<T, string> PermissionKeyColumn)
    {
        return query.Where(pp => context.Permissions
            .Where(p => /*PermissionKeyColumn is in Permissions Table p.PermissionKey  ??????*/)
            .Where(p => true/* another complicated where*/).Any());
    }

用法將是

context.orders.AddComplexWhere(context,o=>o.permissionKey).ToList()..

這樣我就可以繼續重復使用

要實現這一目標,您需要使用

Expression<Func<T, bool>>

這是一個例子:

public static IEnumerable<T> AddComplexWhere<T>(this IEnumerable<T> query, DBContext context, Expression<Func<T, bool>> expression)
    {
        return query.Where(expression).Any());
    }

在此修改之后,您的代碼應該正常工作:

context.orders.AddComplexWhere(context,o=>o.permissionKey == something).ToList()..

暫無
暫無

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

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