List 计算 WhereNot 的扩展方法
Extension Method for List to compute 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);
}
}
}
由于您只想 return 条件不为真的项目,当 func()
return 为假时,每个项目只有 return 个。
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;
}
}
}
我有一项要求是实现 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);
}
}
}
由于您只想 return 条件不为真的项目,当 func()
return 为假时,每个项目只有 return 个。
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;
}
}
}