C# 将 List<int> 转换为逗号分隔值的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9239086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List<int> to string of comma separated values
提问by Ciupaz
having a List<int>of integers (for example: 1 - 3 - 4)
how can I convert it in a string of this type?
有一个List<int>整数(例如:)1 - 3 - 4如何将其转换为这种类型的字符串?
For example, the output should be:
例如,输出应该是:
string values = "1,3,4";
采纳答案by Martijn B
Another solution would be the use of Aggregate. This is known to be much slowerthen the other provided solutions!
另一种解决方案是使用Aggregate。众所周知,这比其他提供的解决方案慢得多!
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.Joinor a StringBuilderinstead.
请参阅下面的评论,为什么不应该使用它。使用String.Join或 aStringBuilder代替。
回答by Albin Sunnanbo
var ints = new List<int>{1,3,4};
var stringsArray = ints.Select(i=>i.ToString()).ToArray();
var values = string.Join(",", stringsArray);
回答by Meysam
var nums = new List<int> {1, 2, 3};
var result = string.Join(", ", nums);
回答by eselk
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();
回答by Yagnesh Khamar
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(); });
回答by Mithun Basak
Use the Stringify.Library nuget package
使用 Stringify.Library nuget 包
Example 1 (Default delimiter is implicitly taken as comma)
示例 1(默认分隔符被隐式视为逗号)
string values = "1,3,4";
var output = new StringConverter().ConvertFrom<List<int>>(values);
Example 2 (Specifying the delimiter explicitly)
示例 2(明确指定分隔符)
string values = "1 ; 3; 4";
var output = new StringConverter().ConvertFrom<List<int>>(values), new ConverterOptions { Delimiter = ';' });

