谓词<int>匹配问题

Pet*_*etr 4 c# syntax predicate anonymous-methods

我不明白以下代码是如何工作的.具体来说,我不明白使用"return i <3".我希望返回i如果它<小于3.我总是认为返回只返回值.我甚至找不到它的语法.

第二个问题,在我看来,使用匿名方法(委托(int i))但是可以用普通委托指向方法else来编写它吗?谢谢

List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 };
List<int> result =
    listOfInts.FindAll(delegate(int i) { return i < 3; });
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

不,return i < 3不一样if (i < 3) return;.

相反,它相当于:

bool result = (i < 3);
return result;
Run Code Online (Sandbox Code Playgroud)

换句话说,它返回评估结果i < 3.因此,如果i为2 则返回true ,但如果i为10 则返回false .

你绝对可以使用方法组转换来编写它:

List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 };
List<int> result = listOfInts.FindAll(TestLessThanThree);

...
static bool TestLessThanThree(int i)
{
    return i < 3;
}
Run Code Online (Sandbox Code Playgroud)