Can a C# lambda expression have more than one statement?

Can a C# lambda expression include more than one statement?

(Edit: As referenced in several of the answers below, this question originally asked about "lines" rather than "statements".)


当然:

List<String> items = new List<string>();

var results = items.Where(i => 
       {
                bool result;

                if (i == "THIS")
                    result = true;
                else if (i == "THAT")
                    result = true;
                else
                    result = false;

                return result;
            }
        );

You can put as many newlines as you want in a lambda expression; C# ignores newlines.

You probably meant to ask about multiple statements.

Multiple statements can be wrapped in braces.

See the documentation.


(I'm assuming you're really talking about multiple statements rather than multiple lines.)

You can use multiple statements in a lambda expression using braces, but only the syntax which doesn't use braces can be converted into an expression tree:

// Valid
Func<int, int> a = x => x + 1;
Func<int, int> b = x => { return x + 1; };        
Expression<Func<int, int>> c = x => x + 1;

// Invalid
Expression<Func<int, int>> d = x => { return x + 1; };
链接地址: http://www.djcxy.com/p/31596.html

上一篇: C#Func委托与lambda表达式组合不正确

下一篇: 一个C#lambda表达式可以有多个语句吗?