Search

Dec 12, 2008

Creating comma separated string from Array - LINQ

Its common requirement to create comma separated string from Array. Using extension methods of LINQ we can do it in single line. Lets create Array first from comma separated values, its simple as we just need to split them using Split function.

string strTest = "1,2,4,6";
string[] Nums = strTest.Split(',');

let's create comma separated string from string Array Nums,

Generally people use foreach loop to create the comma separated string,

But here is the single line code using Lambda Expression to create the same thing.

Console.Write(Nums.Aggregate<string>((first, second) => first + "," + second));
//OUTPUT:
//1,2,4,6

Here the Lambda expression which is accepting two argument and returning the string having concatenation along with delimiter.

3 comments:

Unknown said...

Here's a simpler method for creating a comma delimited string from the array of strings:

String.Join(",", Nums);

Anonymous said...

If Nums is of type int[], then the Aggregate alternative seems like a good idea.

Nacho said...

Tom, I love your method, thanks for sharing.