Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: How do I concatenate a list of integers into comma delimited string?

Tags:

c#

linq

aggregate

It's probably something silly I missed, but I try to concatenate a list of integers instead of summing them with:

integerArray.Aggregate((accumulator, piece) => accumulator+"," + piece)

The compiler complained about argument error. Is there a slick way to do this without having to go through a loop?

like image 750
Haoest Avatar asked May 26 '10 23:05

Haoest


People also ask

How do you convert a List of integers to a comma separated string?

Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string.

How do I concatenate in LINQ query?

In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not support query syntax in C# and VB.NET languages. It support method syntax in both C# and VB.NET languages.

How do I create a comma separated string from a List of strings in C#?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.


4 Answers

Which version of .NET? In 4.0 you can use:

string.Join(",", integerArray);

In 3.5 I would be tempted to just use:

string.Join(",", Array.ConvertAll(integerArray, i => i.ToString()));

assuming it is an array. Otherwise, either make it an array, or use StringBuilder.

like image 171
Marc Gravell Avatar answered Oct 05 '22 13:10

Marc Gravell


You probably want to use String.Join.

string.Join(",", integerArray.Select(i => i.ToString()).ToArray());

If you're using .Net 4.0, you don't need to go through the hassle of reifying an array. and can just do

 string.Join(",", integerArray);
like image 35
48klocs Avatar answered Oct 05 '22 11:10

48klocs


The error you are getting is because you didn't use the override of Aggregate which lets you specify the seed. If you don't specify the seed, it uses the type of the collection.

integerArray.Aggregate("", (accumulator, piece) => accumulator + "," + piece);
like image 20
Samuel Avatar answered Oct 05 '22 13:10

Samuel


Just to add another alternative to @Marc's

var list = string.Join( ",", integerArray.Select( i => i.ToString() ).ToArray() );
like image 29
tvanfosson Avatar answered Oct 05 '22 13:10

tvanfosson