简体   繁体   中英

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".)

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;
            }
        );

(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; };

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 .

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; };
Func<string, bool> test = (name) => 
{
   if (name == "yes") return true;
   else return false;
}

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.

With c# 7.0 You can use like this also

Public string ParentMethod(int i, int x){
    int calculation = (i*x);
    (string info, int result) InternalTuppleMethod(param1, param2)
    {
        var sum = (calculation + 5);
        return ("The calculation is", sum);
    }
}

Let say you have a class:

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    }

With the C# 7.0 inside this class you can do it even without curly brackets:

Action<int, int> action = (x, y) => (_, _) = (X += x, Y += y);

and

Action<int, int> action = (x, y) => _ = (X += x, Y += y);

would be the same as:

Action<int, int> action = (x, y) => { X += x; Y += y; };

This also might be helpful if you need to write the a regular method or constructor in one line or when you need more then one statement/expression to be packed into one expression:

public void Action(int x, int y) => (_, _) = (X += x, Y += y);

or

public void Action(int x, int y) => _ = (X += x, Y += y);

or

public void Action(int x, int y) => (X, Y) = (X + x, Y + y);

More about deconstruction of tuples in the documentation .

Another Example.

var iListOfNumbers = new List<int>() { 1, 2, 3, 4, 5 };

Func<List<int>, int> arithmeticSum = iList =>
{
    var finalResult = 0;
            
    foreach (var i in iList)
        finalResult = finalResult + i;
            
    return finalResult;
};

Console.WriteLine(arithmeticSum.Invoke(iListOfNumbers));
Console.WriteLine(arithmeticSum(iListOfNumbers));
// The above two statements are exactly same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM