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

100
说我为了调试目的,想快速将IEnumerable中的内容转换成一行字符串,并用逗号分隔每个字符串项。我可以使用一个带有foreach循环的辅助方法来实现,但这既不好玩也不简洁。能否使用Linq?还有其他简短的方法吗?

2
可能是重复的问题:IEnumerable to string - Michael Freidgeim
6个回答

159
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));

    }
}

59

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

这将在末尾添加一个多余的逗号,但您可以添加.TrimEnd(',')来摆脱它。 - Robin
3
使用以下代码,您就不需要在结尾处进行修剪了: collection.Aggregate((str, obj) => str + "," + obj.ToString()); - Hoang Minh
4
请注意,这可能会影响性能。Enumerable.Aggregate方法使用加号来连接字符串,速度比String.Join方法慢得多。 - chviLadislav
1
string.join比chviLadislav提到的更便宜,代码也更少。 - Mohamad Hammash

7
(a)设置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) 将 IEnumerable 连接成一个字符串:
// 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();

4
IEnumerable<string> foo = 
var result = string.Join( ",", foo );

2
String.Join末尾的.ToArray()在.NET < 4中是必需的。 - UNeverNo
不是这样的。为什么你需要在字符串上使用.ToArray()呢?那样会失败的。 - undefined

0

要将一系列字符串组合成一个字符串,不要直接使用+,而是使用StringBuilder逐个迭代,或者用String.Join一次性完成。


在连接三个运算符时,编译器将把这些操作转化为调用string.Append方法的一个带有3个参数的。因此,当操作数超过3个时,使用StringBuilder会很方便。 - Johann Gerell
你应该提供一个示例代码。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接