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

后端 未结 8 1183
花落未央
花落未央 2020-11-29 03:37

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\" rath

相关标签:
8条回答
  • 2020-11-29 04:07
    Func<string, bool> test = (name) => 
    {
       if (name == "yes") return true;
       else return false;
    }
    
    0 讨论(0)
  • 2020-11-29 04:13

    Sure:

    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;
                }
            );
    
    0 讨论(0)
  • 2020-11-29 04:13

    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.

    0 讨论(0)
  • 2020-11-29 04:17

    Since C# 7:

    Single line statement:

    int expr(int x, int y) => x + y + 1; 
    

    Multiline statement:

    int expr(int x, int y) { int z = 8; return x + y + z + 1; };
    

    although these are called local functions I think this looks a bit cleaner than the following and is effectively the same

    Func<int, int, int> a = (x, y) => x + y + 1;
    
    Func<int, int, int> b = (x, y) => { int z = 8; return x + y + z + 1; };
    
    0 讨论(0)
  • 2020-11-29 04:21

    (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; };
    
    0 讨论(0)
  • 2020-11-29 04:22

    From Lambda Expressions (C# Programming Guide):

    The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.

    0 讨论(0)
提交回复
热议问题