43

How can I write a LINQ expression (or anything else) that selects an item from a List and join them together?

Example

IList<string> data = new List<string>();

data.Add("MyData1");
data.Add("MyData2");

string result = // Some LINQ query... I try data.Select(x => x + ",");

//result = "MyData1, MyData2"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Melursus
  • 10,328
  • 19
  • 69
  • 103

4 Answers4

89

Just go with (String.Join Method):

string joined = String.Join(",", data.ToArray());

But if it has to be LINQ, you could try:

string joinedLinq = data.Aggregate((i, j) => i + "," + j);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • String.Join was exactly what I needed! – Melursus Apr 21 '10 at 13:24
  • 7
    @Melurus, also note that new in .NET 4, the call to .ToArray() is not necessary, nor does it need to be a collection of strings. string.Join has an overload that accepts `IEnumerable`. – Anthony Pegram Apr 21 '10 at 13:37
  • For those stumbling across this now: I settled on a modified version of this (`Select` instead of `Aggregate`) to avoid the issue with 0 elements or calling `ToArray`; full answer is on a more viewed (easier to find) question: http://stackoverflow.com/a/12734070/957950 – brichins Oct 04 '12 at 19:55
  • @Anthony Pegram: `String.Join(delimiter, IEnumerable)` is the best solution for me! – Silvan Hofer Nov 06 '15 at 11:54
15

You may be tempted to use Aggregate() if you're sticking with LINQ:

IList<int> data = new List<int>();

data.Add(123);
data.Add(456);

var result = data.Select(x => x.ToString()).Aggregate((a,b) => a + "," + b);

I wouldn't recommend this because as I found out the hard way this will fail if the list contains zero items - or was it if it had only one item. I forget, but it fails all the same :-)

String.Join(...) is the best way

In the example above, where the datatype is not a string, you can do this:

string.Join(",", data.Select(x => x.ToString()).ToArray())
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
3

As Anthony Pegram wrote String.Join<T>(delimiter, IEnumerable<T>) is the best solution in .NET 4!

Silvan Hofer
  • 1,361
  • 11
  • 12
2

You can use Aggregate() when you need to join a list into a single aggregated object.

string s = "";
if(data.Count > 0)
  s = data.Aggregate((a, b) => a + ',' + b);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636