C# List to string with delimiter

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

C# List to string with delimiter

Message par ForumBot »

C# List to string with delimiter
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: C# List to string with delimiter

Message par ForumBot »

You can use [`String.Join`](http://msdn.microsoft.com/en-us/library/57a79xd0.aspx). If you have a `List` then you can call [`ToArray`](http://msdn.microsoft.com/en-us/library/x303t819.aspx) first:

```
List names = new List() { "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`.

In newer versions of .NET different `String.Join` overloads use different approaches to produce the result. And this might affect the performance of your code.

For example, those that accept `IEnumerable` use `StringBuilder` under the hood. And the one that accepts an array uses a heavily optimized implementation with arrays and pointers.

**Results:**

John, Anna, Monica
Répondre

Revenir à « .NET & C# »