ChadF
ChadF

Reputation: 1758

Explain C# Aggregate behavior

I'm trying to learn C#, and use Aggregate. I can use reduce no problem in Javascript, but for some reason I cannot get my code to operate.

My end goal is to take a List of chars (which are all numbers), convert them into numbers, Aggregate them, and return a value. For now though, I just want to get Aggregate to work.

I set this before doing any aggregation: int[] test = {1,2,3,4,5};

When I have this code:

int result = test.Aggregate ((current, total) => {
    current += 1;
    current + total;
});

I am told: "Only assignment, call, increment, decrement, and new object expressions can be used as a statement" However I have seen examples of multi-line lambda functions.

I can remove the current += 1; line, and the curly braces and it will work, but my goal is to run several things before each aggregation.

How do I have a lambda expression execute multiple lines of code?

Upvotes: 2

Views: 215

Answers (2)

BlackjacketMack
BlackjacketMack

Reputation: 5692

Lambdas that return a value and use curly braces require a 'return' statement:

int[] test = { 1, 2, 3, 4, 5 };

            int result = test.Aggregate((current, total) =>
            {
                current += 1;
                current += total;

                return current;
            });

Upvotes: 2

Baldrick
Baldrick

Reputation: 11840

current + total is not valid C# in that context. It's only valid in the shorthand form for single line lambdas with no curly braces. Otherwise you need an explicit return statement.

You need to rephrase it as return current + total;

When you use it without the curly braces, the return is implicit.

Upvotes: 3

Related Questions