简体   繁体   中英

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";
var nums = new List<int> {1, 2, 3};
var result = string.Join(", ", nums);
var ints = new List<int>{1,3,4};
var stringsArray = ints.Select(i=>i.ToString()).ToArray();
var values = string.Join(",", stringsArray);

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.

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

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

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 = ';' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM