我有一個要求來實作 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);
}
}
}
uj5u.com熱心網友回復:
由于您只想回傳條件不為真的專案,因此僅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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340918.html
上一篇:C#從子組中選擇重復項
下一篇:C#使用組選擇重復項
