C# List to string with delimiter

Czy istnieje funkcja w C# do szybkiej konwersji pewnej kolekcji na ciąg znaków i oddzielania wartości za pomocą ogranicznika?

Na przykład:

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

Author: bluish, 2010-08-26

3 answers

Możesz użyć String.Join. Jeśli masz List<string> to możesz zadzwonić ToArray pierwszy:

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

W. NET 4 nie potrzebujesz już ToArray, ponieważ istnieje przeciążenie String.Join, które zajmuje IEnumerable<string>.

 765
Author: Quartermeister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-06 12:45:36

Możesz to również zrobić z linq jeśli chcesz

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

Chociaż wolę składnię non-linq w odpowiedzi Quartermeistera i myślę, że Aggregate może wykonywać wolniej(prawdopodobnie więcej operacji łączenia łańcuchów).

 60
Author: Bob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-26 12:36:09
List<string> targets = new List<string>();

var InboxChecked = true;
var BannerChecked = false;
var EmailChecked = true;

if (InboxChecked)
{
    targets.Add("Inbox");
}

if (BannerChecked)
{
    targets.Add("Banner");
}

if (EmailChecked)
{
    targets.Add("Email");
}

var index = 0;

if (targets.Any())
{
    var aggregate = targets.Aggregate((s1, s2) =>
    {
        return ++index == targets.Count - 1 ? s1 + " and " + s2 : s1 + ", " + s2;
    });

    // aggregate.Dump();
}

// returns -> Inbox and Email
 -6
Author: superlogical,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-25 02:20:03