繁体   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