简体   繁体   中英

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.

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