TMan
TMan

Reputation: 4122

Aggregating anonymous types using lambda

I'm trying to print out a list of phone numbers (\n for each number) in a format {type}:{number}. So from a list of 2 numbers I would print out:

 Home: 111-111-1111
 Cell: 222-222-2222

So far I can select into an anonymous type but when I go to aggregate it is leterally printing out the whole anonymous type on the screen looking exactly like below:

 new { phoneType = Home + ": ", phoneNumber = 111-111-1111 }

Should I even be using aggregate? This is what I'm working with:

  PhoneNumbers.Select(x => new { phoneType = x.PhoneType, phoneNumber = x.PhoneNumber1 }).Aggregate(
                (p, x) => new { phoneType = p.phoneType + ": ", x.phoneNumber });

Upvotes: 1

Views: 1100

Answers (2)

Timothy Shields
Timothy Shields

Reputation: 79461

While you could do this with IEnumerable<string>.Aggregate, I feel it's cleaner if you just use string.Join. Someone reading your code will be able to more easily get the meaning out if they see "join these strings with newline."

string.Join(
    Environment.NewLine,
    PhoneNumbers.Select(x =>
        string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50225

If you just want the phone numbers as strings, you can create that string in a Select call:

var x = PhoneNumbers.Select(x => string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));

Your Aggregate call is basically a bug (assuming it even compiles) because you're combining the "current" phone number with the previous phone type. It's also unnecessary for combining the phone numbers as text because of existing string methods:

var phoneNumberStrings = PhoneNumbers.Select(x => string.Format("{0}: {1}", x.PhoneType, x.PhoneNumber));
var text = string.Join(Environment.NewLine, phoneNumberStrings);

Upvotes: 4

Related Questions