How can I write a LINQ expression (or anything else) that selects an item from a List and join them together?
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"
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.
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.
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.
The Join() method in C# is used to concatenate all the elements of a string array, using the specified separator between each element.
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);
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With