Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a List<int> to a comma separated string

Tags:

c#

collections

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. We need to specify the character that will be used as the separator for the elements in the string.

How can I convert an array to comma-separated string?

join method. To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.

How do you make a comma-separated string in Python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].


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

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.


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

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://docs.microsoft.com/en-us/archive/blogs/ericlippert/comma-quibbling

and the StackOverflow commentary:

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


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(", "));

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));

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.