[英]What's the easiest way to convert a list of integers to a string of comma separated numbers in C#
I'm looking for the one liner here, starting with: 我在这里寻找一个班轮,从:
int [] a = {1, 2, 3};
List<int> l = new List<int>(a);
and ending up with 结束
String s = "1,2,3";
String s = String.Join(",", a.Select(i => i.ToString()).ToArray());
string s = string.Join(",", Array.ConvertAll(a, i => i.ToString()));
或者在.NET 4.0中你可以试试 (虽然我不确定它会编译):
string s = string.Join(",", a);
String.Join(",", l);
string.Join(",", l.ConvertAll(i => i.ToString()).ToArray());
假设您在.NET 3.5 w / Linq下进行编译。
int[] array = {1,2,3};
string delimited = string.Join(",", array);
l.Select(i => i.ToString()).Aggregate((s1, s2) => s1 + "," + s2)
另一种方式:
string s = a.Aggregate("", (acc, n) => acc == "" ? n.ToString() : acc + "," + n.ToString());
I know you're looking for a one liner, but if you create an extension method, all future usage is a one liner. 我知道你正在寻找一个衬垫,但如果你创建一个扩展方法,所有未来的使用都是一个衬垫。 This is a method I use. 这是我使用的方法。
public static string ToDelimitedString<T>(this IEnumerable<T> items, string delimiter)
{
StringBuilder joinedItems = new StringBuilder();
foreach (T item in items)
{
if (joinedItems.Length > 0)
joinedItems.Append(delimiter);
joinedItems.Append(item);
}
return joinedItems.ToString();
}
For your list it becomes: l.ToDelimitedString(",")
I added an overload that always uses comma as the delimiter for convenience. 对于你的列表,它变成: l.ToDelimitedString(",")
我添加了一个重载,为了方便,它总是使用逗号作为分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.