Avatar ·

How to create a string with values from IList<string> or IEnumerable<string> separated by commas?

Hello everyone! I'm just starting to learn C# and came across this task: I have a collection of strings (for example, a list of user names), and I need to combine them into a single string where each element is separated by a comma. It sounds simple, but I've tried several approaches and none of them look elegant enough. Here's what I have: ```csharp List names = new List { "Anna", "Ivan", "Maria", "Petr" }; ``` I want to get the output: `"Anna, Ivan, Maria, Petr"`. The problem is that I don't want a comma after the last element. I tried writing a loop with a condition, but the code ends up being cumbersome: ```csharp string result = ""; for (int i = 0; i < names.Count; i++) { result += names[i]; if (i < names.Count - 1) result += ", "; } ```