【发布时间】:2021-10-27 16:49:27
【问题描述】:
我有一个要求是实现 List 的扩展方法以找出 WhereNot。我不打算使用任何现有的 Linq 扩展方法,例如 where 等。
举例
IEnumerable<int> list = new List<int> {1,2,3,4,5,6};
var whereNotListInt = list.WhereNot((num) => num > 3));
foreach(int i in whereNotListInt)
{
Console.WriteLine(i);
}
输出:- 1 2 3
IEnumerable<string> list = new List<string> {"Cat", "Dog"};
var whereNotListStr = list.WhereNot((str) => str.StartsWith("D")));
foreach(string str in whereNotListStr )
{
Console.WriteLine(str);
}
输出:猫
我尝试了以下解决方案,但无法弄清楚如何调用该函数。
public static class Utility
{
public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> list, Func<T, bool> func)
{
foreach (var item in list)
{
yield return func(item);
}
}
}
【问题讨论】:
-
听起来像是功课。你试过什么?有什么东西阻止你遍历集合并过滤掉符合你的条件的东西吗?
-
我也添加了我的解决方案。我一直在调用谓词。
标签: c# linq extension-methods