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.
.NET 4+
IList<string> strings = new List<string>{"1","2","testing"};
string joined = string.Join(",", strings);
Detail & Pre .Net 4.0 Solutions
IEnumerable<string>
può essere convertito in un array di stringhe molto facilmente con LINQ (.NET 3.5):
IEnumerable<string> strings = ...;
string[] array = strings.ToArray();
E'abbastanza facile scrivere il metodo helper equivalente se ne avete bisogno:
public static T[] ToArray(IEnumerable<T> source)
{
return new List<T>(source).ToArray();
}
Poi chiamatelo in questo modo:
IEnumerable<string> 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<string>(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 :)
Puoi usare .ToArray()
su Lists
e IEnumerables
, e poi usare String.Join()
come volevi.