Monday, June 29, 2009

C# Puzzle No.18 (beginner)

Your goal is to convert an array into a string.

int[] TheArray = new int[] { 1, 2, 3, 6, 7, 8 };
string TheArrayString = TheArray.????;
Console.WriteLine( TheArrayString );

Replace the "????" placeholder with a valid C# expression so that the output of the above snippet on the console is:

1, 2, 3, 6, 7, 8


Deto said...

okey, I got cheap solution :)

Normally I would use static string.Join(), and here you have it.

..but - if I have to start as you wrote, then :

string TheArrayString = TheArray.Select(x => string.Join(", ",TheArray.Select(s => s.ToString()).ToArray())).First();

Wiktor Zychla said...

a clue towards more natural solution - Linq can also be used to accumulate, not only to select.

Deto said...

Hmm, indeed.

That pointed me to find "Which LINQ extension method returns simple T, not IEnumerable<T>, and I found Aggregate as interesting.

Here is what I end up with:

string TheArrayString = TheArray.Select(x => x.ToString()).Aggregate((pre,post) => pre+", "+post);

Visit my website