c# - List 计算 WhereNot 的扩展方法
问题描述
我有一个要求来实现 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);
}
}
}
解决方案
由于您只想返回条件不为 true 的项目,因此仅func()
在该项目上返回 false 时返回每个项目。
public static class Utility
{
public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> list, Func<T, bool> func)
{
foreach (var item in list)
{
if (!func(item))
yield return item;
}
}
}
推荐阅读
- android - 如何结合两个查询 FirebaseDatabase?
- mule - 无效字符问题
- web - Content-Security-Policy 中的“self”和“unsafe-inline”有什么区别?
- apache-kafka - 微服务架构模式
- python - SQL UPDATE 不更新 (PYTHON)
- swift - 我应该将 .swiftpm 添加到 gitignore 吗?
- reactjs - React 测试库:状态更改时未删除禁用的属性
- angular - Angular PrimeNG pTree 树节点
- python - 如何在 LoPy4 中设置 LoRa?
- google-sheets - 查找 Google 表格记录并更新为新记录