我遵循本教程关于lambda表达式,并创建了以下代码;
Func<int, bool> isHighNUmber = s => s > 10;
IList<int> intList = new List<int>() { 1, 3,9, 2, 63, 236, 32, 474, 83, 832, 58, 3458, 35, 8, 4 };
Console.WriteLine("All numbers.");
foreach (int x in intList)
{
Console.WriteLine(x);
}
Console.WriteLine("High Numbers");
foreach(int x in intList.Where(isHighNUmber).ToList<int>())
{
Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,现在我想尝试只获得低数字,所以我尝试了
foreach(int x in intList.Where(!isHighNUmber).ToList<int>())
foreach(int x in intList.Where(isHighNUmber == false).ToList<int>())
Run Code Online (Sandbox Code Playgroud)
以及上述语法的变体,但无法使其工作.我还寻找像WhereNot这样的函数
foreach(int x in intList.WhereNot(!isHighNUmber).ToList<int>())
Run Code Online (Sandbox Code Playgroud)
替换where函数但找不到合适的函数.我可以轻松地添加另一个Func来执行与isHighNumber相反的操作,但我想如果该函数非常大,你不会想要完全重写它.我应该如何在where方法中得到lambda Func的反面?
试试这个:
foreach(int x in intList.Where(x=> !isHighNUmber(x)).ToList<int>())
Run Code Online (Sandbox Code Playgroud)
除非你创建isNotHighNumber否定函数,否则你不能使用这个语法糖isHighNumber
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |