gpt4 book ai didi

c# - 如何通过自定义扩展方法使用 C# Linq 谓词

转载 作者:行者123 更新时间:2023-11-30 12:41:25 25 4
gpt4 key购买 nike

我正在尝试编写一个 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()..

这样我就可以继续重用where了

最佳答案

要实现这个你需要使用

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()..

关于c# - 如何通过自定义扩展方法使用 C# Linq 谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com