Problem
Is there a simple LINQ expression that will concatenate all of the entries in my Liststring> collection into a single string with a delimiter character?
What happens if the collection is made up of custom objects rather than strings? Consider the situation when I need to concatenate on object. Name.
Asked by Jobi Joy
Solution #1
String.Join(delimiter, list);
is sufficient.
Answered by Sedat Kapanoglu
Solution #2
Though this response achieves the desired effect, it performs poorly when compared to the other options. If you decide to use it, exercise extreme caution.
This should work if you use LINQ.
string delimiter = ",";
List<string> items = new List<string>() { "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<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();
}
}
And now for my best:)
items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
Answered by Ali Ersöz
Solution #3
Note that the concatenated string in this answer is not generated using LINQ. LINQ can cause major performance issues when used to convert enumerables to delimited strings.
This is for any type that implements IEnumerable, such as an array, list, or any other type that implements IEnumerable:
string.Join(delimiter, enumerable);
And this is true for a variety of custom objects:
string.Join(delimiter, enumerable.Select(i => i.Boo));
This is an example of a string array:
string.Join(delimiter, array);
This is a string for a List:
string.Join(delimiter, list.ToArray());
Also, here’s a collection of custom objects:
string.Join(delimiter, list.Select(i => i.Boo).ToArray());
Answered by Alexander Prokofyev
Solution #4
using System.Linq;
public class Person
{
string FirstName { get; set; }
string LastName { get; set; }
}
List<Person> persons = new List<Person>();
string listOfPersons = string.Join(",", persons.Select(p => p.FirstName));
Answered by dev.bv
Solution #5
That is an excellent question. I’ve been making use of
List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
string joinedString = string.Join(", ", myStrings.ToArray());
It’s not LINQ, but it gets the job done.
Answered by Jacob Proffitt
Post is based on https://stackoverflow.com/questions/559415/concat-all-strings-inside-a-liststring-using-linq