如何将 IEnumable < string > 转换为一个逗号分隔的字符串?

假设出于调试的目的,我想快速将 IEnumable 的内容放入一行字符串中,每个字符串项用逗号分隔。我可以在一个带有 foreach 循环的 helper 方法中完成,但这既不有趣也不简短。Linq 可以用吗?还有其他短路的方法吗?

77055 次浏览
collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
string output = String.Join(",", yourEnumerable);

String.Join Method (String, IEnumerable

Concatenates the members of a constructed IEnumerable collection of type String, using the specified separator between each member.

IEnumerable<string> foo =
var result = string.Join( ",", foo );
using System;
using System.Collections.Generic;
using System.Linq;


class C
{
public static void Main()
{
var a = new []{
"First", "Second", "Third"
};


System.Console.Write(string.Join(",", a));


}
}

to join large array of strings to a string, do not directly use +, use StringBuilder to iterate one by one, or String.Join in one shot.

(a) Set up the IEnumerable:

        // In this case we are using a list. You can also use an array etc..
List<string> items = new List<string>() { "WA01", "WA02", "WA03", "WA04", "WA01" };

(b) Join the IEnumerable Together into a string:

        // Now let us join them all together:
string commaSeparatedString = String.Join(", ", items);


// This is the expected result: "WA01, WA02, WA03, WA04, WA01"

(c) For Debugging Purposes:

        Console.WriteLine(commaSeparatedString);
Console.ReadLine();