为什么这个匿名方法在lambda的情况下不起作用?

Joh*_*n V 3 c# lambda anonymous-function

我正在学习匿名方法,lambdas等,并且找不到它在这里不起作用的原因:

// this does not work
MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; });

// this works
MyDictionary.Keys.Where(w => w.Length == 5);
Run Code Online (Sandbox Code Playgroud)

jav*_*iry 11

你忘记return了陈述的结果:

MyDictionary.Keys.Where(delegate(string s) { return s.Length == 5; });
Run Code Online (Sandbox Code Playgroud)

考虑delegate作为一种完整的方法,除了命名部分之外,必须尽可能与独立的方法相同.所以,你可以把它想象成:

delegate(string s) {
    // you would need to return something here:
    return s.Length == 5; 
}
Run Code Online (Sandbox Code Playgroud)

更新:

另外,想想这两个lambdas:

MyDictionary.Keys.Where(w => w.Length == 5); // works
MyDictionary.Keys.Where(w => { w.Length == 5 }); // does not work
Run Code Online (Sandbox Code Playgroud)

为什么第二个不起作用?这样想就可以更好地了解正在发生的事情.这只是简化图片:

第一个lambda是一个语句:w.Length == 5一个语句有一个实际返回它的结果.没有?

但第二个:{ w.Length == 5 }是一个块.除了明确地执行此操作之外,块不会返回任何内容.