views:

101

answers:

3

How can I write a Linq expression (or anything else) that select 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"
+5  A: 

Why not 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);
astander
see my warning about Aggregate below...
Simon_Weaver
String.Join was exactly what I needed!
Melursus
@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<T>`.
Anthony Pegram
@anthony cool! i hate having to do ToArray()!
Simon_Weaver
A: 

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);
Brian R. Bondy
+1  A: 

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 1 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())
Simon_Weaver
It will throw if the enumerable has no elements. Check for count == 0.
Anthony Pegram