【问题标题】:Extension Method for List to compute WhereNotList 计算 WhereNot 的扩展方法
【发布时间】: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


【解决方案1】:

由于您只想返回条件不成立的项目,因此仅在 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;
        }    
    }
}

【讨论】:

  • 谢谢@Jonathan
猜你喜欢
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 2015-02-12
相关资源
最近更新 更多