简体   繁体   English

在C#中将整数列表转换为逗号分隔数字串的最简单方法是什么?

[英]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.

相关问题 将列表转换为特定属性的逗号分隔字符串的最简单方法? - Easiest way to convert list to a comma separated string by a Specific Property? 将逗号分隔的列表作为数字字符串传递,以使用 Npgsql 作为 C# 中 PostgreSQL db 的整数列表进行查询 - Pass comma-separated list as string of numbers to query as list of integers for PostgreSQL db in C# using Npgsql 在C#中从bool转换为字符串的最简单方法是什么? - What's the easiest way to convert from a bool to string in C#? 从C#中的short []数组中的数字创建逗号分隔字符串的最佳方法是什么? - What is the best way to create a Comma separated String from numbers in a short[] Array in C#? 如何将ac#逗号分隔值字符串转换为列表? - How to convert a c# comma separated values string into a list? 在C#中将数组列表转换为逗号分隔的字符串 - Convert Array List to Comma Separated String in C# 在C#中将列表组合转换为逗号分隔的字符串 - Convert List Combo into Comma-Separated String in c# 将用逗号分隔的数据点字符串转换为List <int> 在C#中 - Convert string of data points separated by comma to List<int> in C# 什么是生成List的最简单方法 <int> C#中的有序数字? - What's the easiest way to generate a List<int> of ordered numbers in C#? C#对逗号分隔的数字进行排序 - C# sort string of comma separated numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM