Ciupaz
Ciupaz

Reputation: 699

Convert List<int> to string of comma separated values

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

For example, the output should be:

string values = "1,3,4";

Upvotes: 29

Views: 70290

Answers (6)

Mithun Basak
Mithun Basak

Reputation: 11

Use the Stringify.Library nuget package

Example 1 (Default delimiter is implicitly taken as comma)

string values = "1,3,4";
var output = new StringConverter().ConvertFrom<List<int>>(values);

Example 2 (Specifying the delimiter explicitly)

string values = "1 ; 3; 4";
var output = new StringConverter().ConvertFrom<List<int>>(values), new ConverterOptions { Delimiter = ';' });

Upvotes: 0

Yagnesh Khamar
Yagnesh Khamar

Reputation: 182

You can use the delegates for the same

List<int> intList = new List<int>( new int[] {20,22,1,5,1,55,3,10,30});
string intStringList = string.Join(",", intList.ConvertAll<string>(delegate (int i) { return i.ToString(); });

Upvotes: 0

eselk
eselk

Reputation: 6894

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(',');
    List<int> list = new List<int>();
    foreach (string s in ss)
        list.Add(Int32.Parse(s));
    return (list);
}

Usage:

String s = "1,2,3,4";
List<int> list = s.CommaStringToIntList();
list.Add(5);
s = list.ToCommaString();
s += ",6";
list = s.CommaStringToIntList();

Upvotes: 0

Martijn B
Martijn B

Reputation: 4075

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.

Upvotes: 15

Meysam
Meysam

Reputation: 18177

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

Upvotes: 115

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47068

var ints = new List<int>{1,3,4};
var stringsArray = ints.Select(i=>i.ToString()).ToArray();
var values = string.Join(",", stringsArray);

Upvotes: 20

Related Questions