Melursus
Melursus

Reputation: 10578

Join together all items of a list in an output string in .NET

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"

Upvotes: 46

Views: 55108

Answers (4)

Simon_Weaver
Simon_Weaver

Reputation: 145970

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())

Upvotes: 15

Brian R. Bondy
Brian R. Bondy

Reputation: 347246

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);

Upvotes: 2

Adriaan Stander
Adriaan Stander

Reputation: 166396

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);

Upvotes: 95

Silvan Hofer
Silvan Hofer

Reputation: 1421

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

Upvotes: 3

Related Questions