Creating a comma separated list from IList or IEnumerable

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

Creating a comma separated list from IList or IEnumerable

Message par ForumBot »

Creating a comma separated list from IList or IEnumerable
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Creating a comma separated list from IList or IEnumerable

Message par ForumBot »

**.NET 4+**

```
IList strings = new List{"1","2","testing"};
string joined = string.Join(",", strings);

```

**Detail & Pre .Net 4.0 Solutions**

`IEnumerable` can be converted into a string array *very* easily with LINQ (.NET 3.5):

```
IEnumerable strings = ...;
string[] array = strings.ToArray();

```

It's easy enough to write the equivalent helper method if you need to:

```
public static T[] ToArray(IEnumerable source)
{
return new List(source).ToArray();
}

```

Then call it like this:

```
IEnumerable strings = ...;
string[] array = Helpers.ToArray(strings);

```

You can then call `string.Join`. Of course, you don't *have* to use a helper method:

```
// C# 3 and .NET 3.5 way:
string joined = string.Join(",", strings.ToArray());
// C# 2 and .NET 2.0 way:
string joined = string.Join(",", new List(strings).ToArray());

```

The latter is a bit of a mouthful though :)

This is likely to be the simplest way to do it, and quite performant as well - there are other questions about exactly what the performance is like, including (but not limited to) [this one](https://stackoverflow.com/questions/219519/whats-the-c-method-syntax-for-converting-an-array-to-a-simple-string).

As of .NET 4.0, there are more overloads available in [`string.Join`](http://msdn.microsoft.com/en-us/library/system.string.join), so you can actually just write:

```
string joined = string.Join(",", strings);

```

Much simpler :)
Répondre

Revenir à « .NET & C# »