Question with predicate <int>
I do not understand how the following code works. In particular, I do not understand the use of "return i <3". I would expect a return I IF it <than 3. I always, although this return just returns a value. I could not even find what the syntax is.
Secondly, it seems to me that I am using an anonymous method (delegate (int i)), but is it possible to write it with a normal delegate pointing to the elsewere method? Thanks
List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 }; List<int> result = listOfInts.FindAll(delegate(int i) { return i < 3; }); No, return i < 3 does not match if (i < 3) return; .
Instead, it is equivalent to:
bool result = (i < 3); return result; In other words, it returns the estimated result i < 3 . Therefore, it will return true if i is 2, but false if i is 10. For example,
You can definitely write this down using method group conversion:
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; } You can also write your example using the lambda expression:
var listOfInts = new List<int> { 1, 2, 3, 4, 5 }; var result = listOfInts.FindAll(i => i < 3); Other interesting examples:
var listOfInts = new List<int> { 1, 2, 3, 4, 5 }; var all = listOfInts.FindAll(i => true); var none = listOfInts.FindAll(i => false);