c# - 如何使用谓词在 C# 中创建扩展方法

标签 c# visual-studio linq extension-methods

我正在尝试创建一个名为 RemoveWhere 的扩展方法,它根据谓词从 List 集合中删除一个项目。例如

var result = products.RemoveWhere(p => p.ID == 5);

我使用 Microsoft 的 Where 扩展方法签名作为起点。这是我到目前为止所拥有的:

public static List<T> RemoveWhere<T>(this List<T> source, Func<T, List<T>> predicate)
{
    if (source == null)
    {
        throw new ArgumentNullException("source", "The sequence is null and contains no elements.");
    }

    if (predicate == null)
    {
        throw new ArgumentNullException("predicate", "The predicate function is null and cannot be executed.");
    }

    // how to use predicate here???

}

我不知道如何使用谓词。有人可以帮我完成这个吗?谢谢!

最佳答案

Predicate 参数应该是:Func<T,bool>

public static List<T> RemoveWhere<T>(this List<T> source, Func<T, bool > predicate)
{
    if (source == null)
    {
        throw new ArgumentNullException("source", "The sequence is null and contains no elements.");
    }

    if (predicate == null)
    {
        throw new ArgumentNullException("predicate", "The predicate function is null and cannot be executed.");
    }

    // how to use predicate here???
    var result = new List<T>();
    foreach(var item in source)
    {
        if(!predicate(item))
        {
            result.Add(item);
        }
    }

    return result;
}

编辑: 正如其他人所指出的,此方法要么命名错误,要么已存在于 List 中。我的猜测只是您试图了解方法本身如何使用传入的委托(delegate)。为此,您可以查看我的样本。如果这不是您的意图,我会删除这个答案,因为代码确实有点毫无意义。

关于c# - 如何使用谓词在 C# 中创建扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444238/

相关文章:

c# - 嵌套字典: group by date and then group by Enum value and summarize the count

.net - LINQ 到 XML。枚举没有结果?

C# 方括号和大于/小于

c# - 两个接口(interface)有相同的方法

c# - 将 DB Connection 对象传递给方法

c# - 找不到类型或命名空间名称 'MySql'(是否缺少 using 指令或程序集引用?)c# VS 2013

visual-studio - 如何在 Nuget 的 install.ps1 中添加 PreBuildEvent

c# - Visual Studio 如何在不中断其 IEnumerator<T> 的 MoveNext 的情况下评估 IEnumerable?

visual-studio - 无需MSDN从VS2008 Pro升级到VS2010 Pro

linq - 使用 C# .Net 4.0 LINQ 嵌入逗号的 CSV