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

C#Lambda

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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

    

Solution 5 - C#

Func<string, bool> test = (name) => 
{
   if (name == "yes") return true;
   else return false;
}

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution 8 - C#

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

Solution 9 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpaseenaView Question on Stackoverflow
Solution 1 - C#RQDQView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#SLaksView Answer on Stackoverflow
Solution 4 - C#BigChiefView Answer on Stackoverflow
Solution 5 - C#PolityView Answer on Stackoverflow
Solution 6 - C#jfsView Answer on Stackoverflow
Solution 7 - C#VivekDevView Answer on Stackoverflow
Solution 8 - C#jigar prajapatiView Answer on Stackoverflow
Solution 9 - C#KonardView Answer on Stackoverflow