将List <int>转换为逗号分隔值</int>的字符串

时间:2012-02-11 09:19:09

标签: c# list

拥有List<int>个整数(例如:1 - 3 - 4) 如何将其转换为此类型的字符串?

例如,输出应为:

string values = "1,3,4";

6 个答案:

答案 0 :(得分:83)

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

答案 1 :(得分:18)

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

答案 2 :(得分:12)

另一种解决方案是使用Aggregate。众所周知,这比其他提供的解决方案慢得多

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

请参阅下面的评论,为什么不应该使用它。请改用String.JoinStringBuilder

答案 3 :(得分:0)

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

用法:

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

答案 4 :(得分:0)

您可以使用相同的委托

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

答案 5 :(得分:0)

使用Stringify.Library nuget包

示例1(默认定界符隐含为逗号)

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

示例2(明确指定分隔符)

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