C# 如何转换IEnumerable<;字符串>;到一个逗号分隔的字符串?

C# 如何转换IEnumerable<;字符串>;到一个逗号分隔的字符串?,c#,string,linq,collections,ienumerable,C#,String,Linq,Collections,Ienumerable,假设出于调试目的,我希望快速将IEnumerable的内容放入一行字符串中,每个字符串项以逗号分隔。我可以在带有foreach循环的helper方法中完成,但这既不有趣也不简单。可以使用Linq吗?还有别的捷径吗 collection.Aggregate("", (str, obj) => str + obj.ToString() + ","); 连接构造的IEnumerable集合的成员 键入字符串,在每个成员之间使用指定的分隔符 IEnumerable foo= var resul

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

collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");

连接构造的IEnumerable集合的成员 键入字符串,在每个成员之间使用指定的分隔符

IEnumerable foo=
var result=string.Join(“,”,foo);

若要将大量字符串连接到字符串,请不要直接使用+、使用StringBuilder逐个迭代或字符串。一次连接。

(a)设置IEnumerable: (c) 出于调试目的:
OT:对于3个操作数的串联,编译器将把这些操作转换为一个字符串调用。使用3个参数的Append方法。因此,有了3个以上的操作数,StringBuilder就派上了用场。String.Join结尾处的.ToArray()是.NET<4可能的副本,它会在结尾处添加多余的逗号,但您可以添加
.TrimEnd(',')
来摆脱它。这样做,您就不需要在
collection.Aggregate((str,obj)=>str+,)结尾处进行修剪+obj.ToString())注意这是一个潜在的性能问题。聚合方法使用加号连接字符串。它比String.Join方法慢得多。
string output = String.Join(",", yourEnumerable);
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));

    }
}
        // 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" };
        // Now let us join them all together:
        string commaSeparatedString = String.Join(", ", items);

        // This is the expected result: "WA01, WA02, WA03, WA04, WA01"
        Console.WriteLine(commaSeparatedString);
        Console.ReadLine();