mrblah
mrblah

Reputation: 103497

Converting a List<int> to a comma separated string

Is there a way to take a List and convert it into a comma separated string?

I know I can just loop and build it, but somehow I think some of you guys a more cool way of doing it?

I really want to learn these types of 'tricks', so please explain or link to the docs on the method you use.

Upvotes: 159

Views: 128660

Answers (8)

Eric Lippert
Eric Lippert

Reputation: 660004

For approximately one gazillion solutions to a slightly more complicated version of this problem -- many of which are slow, buggy, or don't even compile -- see the comments to my article on this subject:

https://learn.microsoft.com/en-us/archive/blogs/ericlippert/comma-quibbling

and the StackOverflow commentary:

Eric Lippert's challenge "comma-quibbling", best answer?

Upvotes: 6

cdiggins
cdiggins

Reputation: 18203

For extra coolness I would make this an extension method on IEnumerable<T> so that it works on any IEnumerable:

public static class IEnumerableExtensions {
  public static string BuildString<T>(this IEnumerable<T> self, string delim = ",") {
    return string.Join(delim, self)        
  }
}

Use it as follows:

List<int> list = new List<int> { 1, 2, 3 };
Console.WriteLine(list.BuildString(", "));

Upvotes: 4

user10304366
user10304366

Reputation:

you can use, the System.Linq library; It is more efficient:

using System.Linq;
string str =string.Join(",", MyList.Select(x => x.NombreAtributo));

Upvotes: 0

user1774417
user1774417

Reputation:

Simple solution is

List<int> list = new List<int>() {1,2,3};
string.Join<int>(",", list)

I used it just now in my code, working funtastic.

Upvotes: 171

Larsenal
Larsenal

Reputation: 51146

My "clever" entry:

        List<int> list = new List<int> { 1, 2, 3 };
        StringBuilder sb = new StringBuilder();
        var y = list.Skip(1).Aggregate(sb.Append(x.ToString()),
                    (sb1, x) =>  sb1.AppendFormat(",{0}",x));

        // A lot of mess to remove initial comma
        Console.WriteLine(y.ToString().Substring(1,y.Length - 1));

Just haven't figured how to conditionally add the comma.

Upvotes: 1

Gregory
Gregory

Reputation: 501

Seems reasonablly fast.

IList<int> listItem = Enumerable.Range(0, 100000).ToList();
var result = listItem.Aggregate<int, StringBuilder, string>(new StringBuilder(), (strBuild, intVal) => { strBuild.Append(intVal); strBuild.Append(","); return strBuild; }, (strBuild) => strBuild.ToString(0, strBuild.Length - 1));

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

List<int> list = new List<int> { 1, 2, 3 };
Console.WriteLine(String.Join(",", list.Select(i => i.ToString()).ToArray()));

Upvotes: 11

Pavel Minaev
Pavel Minaev

Reputation: 101565

List<int> list = ...;
string.Join(",", list.Select(n => n.ToString()).ToArray())

Upvotes: 234

Related Questions