C# String Join

The String.Join() method is used to concatenate an array or collection of strings, inserting a separator between each element.

Key Topics

1. Joining Arrays

Example: Joining an Array of Strings

string[] words = {"Hello", "World", "!"};
string joinedString = string.Join(" ", words);
Console.WriteLine(joinedString);  // Outputs: Hello World !

Output:

Hello World !

2. Joining Collections

Example: Joining a List of Strings

List<string> items = new List<string> { "Apple", "Banana", "Cherry" };
string result = string.Join(", ", items);
Console.WriteLine(result); // Outputs: Apple, Banana, Cherry

Output:

Apple, Banana, Cherry

3. Practical Examples

Example: Creating a CSV Line

string[] data = { "John", "Doe", "30" };
string csvLine = string.Join(",", data);
Console.WriteLine(csvLine); // Outputs: John,Doe,30

Key Takeaways

  • The String.Join() method concatenates elements of an array or collection using a specified separator.
  • It is useful for creating formatted strings like CSV lines or lists.
  • You can join any enumerable collection that contains strings.