Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm reading a book and I have problems understanding this code:
List<int> evenNumbers = list.FindAll(delegate(int i) 
{ 
   return (i % 2) == 0;
}; 


I cannot understand what will happen with this code. Who passes the argument to the parameter i and how? I'm really confused.

What I have tried:

Thinking about this but I cannot understand what's happening exactly.
Posted
Updated 23-Mar-18 7:31am
v2
Comments
Richard Deeming 23-Mar-18 14:58pm    
When in doubt, you can almost always view the source of the built-in methods to see how they're implemented:
List<T>.FindAll[^]

For every element in the List 'list' the .NET method 'FindAll' calls the delegate method to get a value (true or false) indicating whether the value should be added to the List 'evenNumbers'. So, the .NET method 'FindAll' passes the value i to the delegate method.

https://msdn.microsoft.com/nl-nl/library/windows/desktop/fh1w7y8z(v=vs.85).aspx[^]
 
Share this answer
 
Comments
The_Unknown_Member 23-Mar-18 13:33pm    
Ohhh, I got it... I'm passing the anonymous method to the Predecate<t> parameter of the method. Am I right?
[no name] 23-Mar-18 13:35pm    
Yes, you're right!
The_Unknown_Member 23-Mar-18 13:40pm    
Thanks!!!
[no name] 23-Mar-18 13:42pm    
You're welcome! Thanks for the answer and vote.
The_Unknown_Member 23-Mar-18 15:23pm    
One last question:How does FindAll not accept anything other than a boolean value. I want to know this particular detail of the implementation. It's a generic method but it works only with boolean values and when I try to return an int for example the compiler gives error: "Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type".

The delegate is generic too.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900