Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
like image 480
Melursus Avatar asked Apr 21 '10 03:04

Melursus


People also ask

How to join list items in c#?

In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it.

How do I join a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How to print all elements in a list c#?

The simplest method to access the elements is by using the for loop. We can access the individual items in the list by their index, months[i] , and then print the element using the Console. WriteLine() method.

How to join array of string in c#?

The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.


2 Answers

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); 
like image 67
Adriaan Stander Avatar answered Oct 11 '22 15:10

Adriaan Stander


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()) 
like image 28
Simon_Weaver Avatar answered Oct 11 '22 15:10

Simon_Weaver