Gyuri
Gyuri

Reputation: 4882

What's the easiest way to convert a list of integers to a string of comma separated numbers in C#

I'm looking for the one liner here, starting with:

int [] a = {1, 2, 3};
List<int> l = new List<int>(a);

and ending up with

String s = "1,2,3";

Upvotes: 3

Views: 346

Answers (8)

Michael Bray
Michael Bray

Reputation: 15265

string.Join(",", l.ConvertAll(i => i.ToString()).ToArray());

This is assuming you are compiling under .NET 3.5 w/ Linq.

Upvotes: 2

Matt H
Matt H

Reputation: 7389

I know you're looking for a one liner, but if you create an extension method, all future usage is a one liner. This is a method I use.


public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
    StringBuilder joinedItems = new StringBuilder();
    foreach (T item in items)
    {
        if (joinedItems.Length > 0)
            joinedItems.Append(delimiter);

        joinedItems.Append(item);
    }

    return joinedItems.ToString();
}

For your list it becomes: l.ToDelimitedString(",") I added an overload that always uses comma as the delimiter for convenience.

Upvotes: -1

Erlend
Erlend

Reputation: 4416

l.Select(i => i.ToString()).Aggregate((s1, s2) => s1 + "," + s2)

Upvotes: 1

primodemus
primodemus

Reputation: 516

Another way of doing it:

string s = a.Aggregate("", (acc, n) => acc == "" ? n.ToString() : acc + "," + n.ToString());

Upvotes: 0

Kris Krause
Kris Krause

Reputation: 7326

int[] array = {1,2,3};

string delimited = string.Join(",", array);

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062650

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

or in .NET 4.0 you could try (although I'm not sure it will compile):

string s = string.Join(",", a);

Upvotes: 6

womp
womp

Reputation: 116977

  String.Join(",", l);

Upvotes: 4

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

String s = String.Join(",", a.Select(i => i.ToString()).ToArray());

Upvotes: 9

Related Questions