Creare una lista separata da virgole da IList o IEnumerable

Qual è il modo più pulito per creare un elenco separato da virgole di valori stringa da una IList<string> o IEnumerable<string>?

String.Join(...) opera su una stringa[] quindi può essere macchinoso lavorarci quando tipi come IList<string> o IEnumerable<string> non possono essere facilmente convertiti in un array di stringhe.

Soluzione

.NET 4+

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

Detail & Pre .Net 4.0 Solutions

IEnumerable può essere convertito in un array di stringhe molto facilmente con LINQ (.NET 3.5):

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

E'abbastanza facile scrivere il metodo helper equivalente se ne avete bisogno:

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

Poi chiamatelo in questo modo:

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

Potete quindi chiamare stringa.Join. Naturalmente, non devi usare un metodo helper:

// 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());

Quest'ultimo è un po' un bocconcino però :)

Questo è probabilmente il modo più semplice per farlo, e anche abbastanza performante - ci sono altre domande su come sono esattamente le prestazioni, incluso (ma non limitato a) questo.

A partire da .NET 4.0, ci sono più sovraccarichi disponibili in string.Join, quindi puoi effettivamente solo scrivere:

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

Molto più semplice :)

Commentari (6)

potete convertire l'IList in un array usando ToArray e poi eseguire un comando string.join sull'array.

Dim strs As New List(Of String)
Dim arr As Array
arr = strs.ToArray
Commentari (0)

Puoi usare .ToArray() su Lists e IEnumerables, e poi usare String.Join() come volevi.

Commentari (0)