开发者

C# List<string> to string with delimiter

开发者 https://www.devze.com 2023-01-13 09:17 出处:网络
Is there a function in C# to quickly convert some col开发者_运维百科lection to string and separate values with delimiter?

Is there a function in C# to quickly convert some col开发者_运维百科lection to string and separate values with delimiter?

For example:

List<string> names --> string names_together = "John, Anna, Monica"


You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica


You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).

0

精彩评论

暂无评论...
验证码 换一张
取 消