Visual Studio - 如何使用谓词在 C# 中创建扩展方法
本文关键字:创建 扩展 方法 谓词 Studio 何使用 Visual | 更新日期: 2023-09-27 17:59:54
我正在尝试创建一个名为RemoveWhere的扩展方法,该方法基于谓词从List集合中删除项目。例如
VaR 结果 = 产品。删除位置(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???
}
我不知道如何使用谓词。有人可以帮我完成这个吗?谢谢!
谓词参数应为: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;
}
编辑:正如其他人指出的那样,此方法要么命名错误,要么已经存在于列表中。我的猜测只是您正在尝试了解方法本身如何使用传入的委托。为此,您可以查看我的示例。如果这不是您的意图,我将删除此答案,因为代码确实毫无意义。
列表中已经有一个方法可以尝试。谓词应该是谓词,然后您可以使用 source。全部删除(谓词(
正如其他人指出的那样,List<T>.RemoveAll
会做你想做的事。但是,如果这是一种学习体验,或者您想在任何IList<T>
(没有RemoveAll
(上进行操作,这应该与RemoveAll
相同,但作为扩展方法。
public static void RemoveWhere<T>(this IList<T> source, Func<T, bool> predicate)
{
//exceptions here...
// how to use predicate here???
for(int c = source.Count-1 ; c >= 0 ; c--)
{
if(predicate(source[c]))
{
source.RemoveAt(c);
}
}
}
正如博卡所观察到的,List<T>
已经有一种方法可以做到这一点。 但是,一个更大的问题是,这实际上不是您应该创建新的扩展方法的情况。 已经有一个接受谓词的扩展方法:Where
。
当然,这样做:
var result = list.Where(x => x != 5).ToList();
比使用RemoveAll
多一点代码:
list.RemoveAll(x => x == 5);
但:
- 它还会构建一个新列表,而不是就地修改现有列表,
-
list
实际上可以是任何IEnumerable<T>
,而不仅仅是一个List<T>
, Where
方法是一种常用的、文档记录良好的扩展方法,任何技能合理的 C# 程序员都可以在看到时识别出来。- 任何阅读该代码的人都很清楚它正在创建一个新列表,并且
- 如果不想创建新列表,只需省略
ToList()
并枚举result
。
我真的很难想象我想为IEnumerable<T>
编写一个采用谓词的扩展方法的情况。 通过使您有可能不使用Where()
,您节省的很少。