我正在尝试创建一个名为 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/