c# - Linq Func 委托(delegate) - 可以添加到吗?

标签 c# linq

下面有一个方法。

如果可能的话,除了通过 func 变量传递之外,我还想添加一些标准过滤:

.Where(p => p.IsLive)

我当然可以在函数字符串本身中传递它,但是,我需要记住每次都这样做。我已经尝试了多种将它与 func 变量合并的方法,但还没有设法破解语法(如果可能的话)。有什么建议吗?

Product GetProduct(Func<Product, bool> func)
{
    return CompareView.Select()
        .Where(func) // Need to add std filtering here
        .FirstOrDefault();
}

最佳答案

最简单的方法就是将另一个调用链接到 Where:

Product GetProduct(Func<Product, bool> func)
{
    return CompareView.Select()
        .Where(p => p.IsLive)
        .Where(func)
        .FirstOrDefault();
}

可以像这样创建一个新委托(delegate):

Product GetProduct(Func<Product, bool> func)
{
    return CompareView.Select()
        .Where(p => p.IsLive && func(p))
        .FirstOrDefault();
}

...但我个人认为这不像 where-composition 方法那么简单。

关于c# - Linq Func 委托(delegate) - 可以添加到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164300/

相关文章:

linq - F# Power Pack Linq 问题

c# - 从对象列表中分组和过滤 c#

c# - 从 c# 中的 list<object> 列表中删除重复的内部列表

c# - 在编译时生成一个 Guid

c# - 无法使用 C# 从 API 获取 json 响应

c# - MySql.Data.MySqlClient.MySqlException (0x80004005) 异常

c# - MVC LINQ - 在相关表中使用 Contains 搜索/查询文本

c# - 如何将 WorkItemCollection 转换为列表

c# - 无法通过 linq 从 ef 读取数据

c# - 如何使用 C# 从时间格式大于 24 小时的字符串中获取总秒数