How to concatenate all strings from List<string> into one string using LINQ?
Hello everyone! I've just started learning C# and LINQ, and I've encountered this task: I have a list of strings `List`, and I want to concatenate them all into one string, separated by commas. For example, the list `{ "apple", "banana", "cherry" }` should become `"apple,banana,cherry"`.
I know that I can use a `foreach` loop and just add strings with `+`, but I was told that LINQ has a more elegant way. However, I can't find the right method. I tried `Aggregate`, but it adds an extra comma at the end, and I don't know how to fix it. Here's my code:
```csharp
List fruits = new List { "apple", "banana", "cherry" };
string result = fruits.Aggregate((a, b) => a + "," + b);
Console.WriteLine(result); // Outputs "apple,banana,cherry" — seems to work
```
No answers yet.
Log in to leave an answer