HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

Concat all strings inside a List<string> using LINQ

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
linqstringsusingconcatliststringallinside

Problem

Is there any easy LINQ expression to concatenate my entire List collection items to a single string with a delimiter character?

What if the collection is of custom objects instead of string? Imagine I need to concatenate on object.Name.

Solution

Warning - Serious Performance Issues

Though this answer does produce the desired result, it suffers from poor performance compared to other answers here. Be very careful about deciding to use it

By using LINQ, this should work;

string delimiter = ",";
List items = new List() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));


class description:

public class Foo
{
    public string Boo { get; set; }
}


Usage:

class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        List items = new List() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
            new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };

        Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}


And here is my best :)

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

Code Snippets

string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));
public class Foo
{
    public string Boo { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
            new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };

        Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}
items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

Context

Stack Overflow Q#559415, score: 566

Revisions (0)

No revisions yet.