Matt
Matt

Reputation: 5511

List.Aggregate unexpected result

When I run this code:

List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");

string s = list.Aggregate((total, item) => total += item + ",");

I expect s to be:

a,b,c,d,

but instead, s is:

ab,c,d,

can anyone tell me why it's not appending a comma between the first and second index?

Thanks

Upvotes: 0

Views: 277

Answers (3)

Steve
Steve

Reputation: 216333

Tried and works

string s = list.Aggregate((total, item) => total += "," + item); 

The problem is: When the runtime calls Aggregate Func for the first time total is "a" and item is "b". Really this extensions was designed to perform calcs not to concatenate strings.

However take note that the resulting string is a,b,c,d (without the ending comma) I don't know if this is preferable or not (depends on your use of the resulting string)

Upvotes: 1

Phil
Phil

Reputation: 43011

You will find that this works

string s = list.Aggregate(string.Empty, (total, item) => total += item + ",");

You can see why if you test this:

var total = "a";
var item = "b";
var s = total += item + ",";

This results in "ab,"

Using an initial empty seed value for total (either (string)null or string.Empty) will give you the expected result.

Upvotes: 3

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

The following overload of Aggregate will work:

string s = list.Aggregate<string, string>(null, (total, item) => total + item + ",");

Basically, the version you're using puts the "a" as the value of total as the initial condition, then appends the rest on using the supplied lambda. My version starts the total out with null and then appends each item on.

Upvotes: 2

Related Questions