I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here:
// this does not work
MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; });
// this works
MyDictionary.Keys.Where(w => w.Length == 5);
I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here:
// this does not work
MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; });
// this works
MyDictionary.Keys.Where(w => w.Length == 5);
You forgot to
return
the result of statement:Think about
delegate
as a complete method which have to be as same as possible to an independent method, except the naming part. So, you can imagine it as:UPDATE:
Also, think about these 2 lambdas:
Why the second one is not working? Think this way to getting a better vision of what's happening. It's just about simplifying the picture:
The first lambda is a statement:
w.Length == 5
and a statement has a result which returns it actually. Doesn't?But the second one:
{ w.Length == 5 }
is a block. And a block does not return anything, except you explicitly do it.