首页 > 解决方案 > 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);
            }    
        }
    }

标签: c#linqextension-methods

解决方案


由于您只想返回条件不为 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;
        }    
    }
}

推荐阅读