Take the 2-minute tour ×

having a List of integers (for example: 1 - 3 - 4) how can I convert it in a string of this type:

string values = "1,3,4";

Thanks in advance.


share|improve this question
add comment

4 Answers

up vote 4 down vote accepted

Another solution would be the use of Aggregate. This is known to be much slower then the other provided solutions!

var ints = new List<int>{1,2,3,4};
var strings =
            ints.Select(i => i.ToString(CultureInfo.InvariantCulture))
                .Aggregate((s1, s2) => s1 + ", " + s2);

See comments below why you should not use it. Use String.Join or a StringBuilder instead.

share|improve this answer
-1 Notoriously bad solution to create strings like this (especially when the list is long). String.Join or StringBuilder are the way to go. Sad for Stack Overflow that a low quality OP does not even know how to accept the best answer. –  Gert Arnold Feb 12 '12 at 10:53
@GertArnold I agree with you. Just wanted to show another solution and forgot to mention anything performance. I tried to delete this answer but I can't. I will update the answer to not use it. –  Martijn B Feb 12 '12 at 11:47
That's very generous. Removed the downvote. –  Gert Arnold Feb 12 '12 at 12:12
add comment
var nums = new List<int> {1, 2, 3};
var result = string.Join(", ", nums);
share|improve this answer
Thank you Meysam –  Ciupaz Feb 11 '12 at 13:42
Note that this doesn't work in .NET 3.5 and earlier (the second parameter must be a string[]). See Albin Sunnanbo's answer. –  Itison Jan 9 '13 at 21:21
add comment
var ints = new List<int>{1,3,4};
var stringsArray = ints.Select(i=>i.ToString()).ToArray();
var values = string.Join(",", stringsArray);
share|improve this answer
Thank you Albin. E for the revers task, from a string of integer with commas, I need to obtain a List<int>. Luigi –  Ciupaz Feb 11 '12 at 9:24
In .NET 4 String.Join has an overload taking an IEnumerable<T> so this can be done without the intermediate array (this overload calls ToString() on each input element): string.Join(",", ints). –  Richard Feb 11 '12 at 9:25
@Ciupaz, for the reverse task, use String.Split(). –  Albin Sunnanbo Feb 11 '12 at 11:44
add comment
public static string ToCommaString(this List<int> list)
    if (list.Count <= 0)
        return ("");
    if (list.Count == 1)
        return (list[0].ToString());
    System.Text.StringBuilder sb = new System.Text.StringBuilder(list[0].ToString());
    for (int x = 1; x < list.Count; x++)
        sb.Append("," + list[x].ToString());
    return (sb.ToString());

public static List<int> CommaStringToIntList(this string _s)
    string[] ss = _s.Split(',');
    foreach (string s in ss)
    return (list);


String s = "1,2,3,4";
List<int> list = s.CommaStringToIntList();
s = list.ToCommaString();
s += ",6";
list = s.CommaStringToIntList();
share|improve this answer
add comment

Your Answer


