说我为了调试目的,想快速将IEnumerable中的内容转换成一行字符串,并用逗号分隔每个字符串项。我可以使用一个带有foreach循环的辅助方法来实现,但这既不好玩也不简洁。能否使用Linq?还有其他简短的方法吗?
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));
}
}
string output = String.Join(",", yourEnumerable);
String.Join方法(String,IEnumerable)
使用指定的分隔符将构造的IEnumerable字符串集合的成员连接在一起。
collection.Aggregate("", (str, obj) => str + obj.ToString() + ",");
.TrimEnd(',')
来摆脱它。 - Robincollection.Aggregate((str, obj) => str + "," + obj.ToString());
- Hoang Minh// 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();
IEnumerable<string> foo =
var result = string.Join( ",", foo );
要将一系列字符串组合成一个字符串,不要直接使用+
,而是使用StringBuilder
逐个迭代,或者用String.Join
一次性完成。