How to join strings in C#
The string.Join() method in C# concatenates elements of a collection with a specified separator. It's the preferred way to join multiple strings efficiently, better than using + in loops.
string.Join() accepts any IEnumerable<T> and converts each element to a string automatically. For arrays and lists of strings, it's particularly straightforward.
For complex scenarios with many concatenations, consider StringBuilder, but for simple joins, string.Join() is cleaner and just as efficient.
C# Example Code
using System;
using System.Collections.Generic;
using System.Linq;
public class JoinStrings
{
public static void Main(string[] args)
{
// Basic string.Join with array
string[] words = { "Hello", "World", "from", "C#" };
string sentence = string.Join(" ", words);
Console.WriteLine(sentence); // Hello World from C#
// Join with different separator
string csv = string.Join(", ", words);
Console.WriteLine(csv); // Hello, World, from, C#
// Join list of strings
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string nameList = string.Join(", ", names);
Console.WriteLine($"Names: {nameList}");
// Join numbers (automatically converted to strings)
int[] numbers = { 1, 2, 3, 4, 5 };
string numberString = string.Join("-", numbers);
Console.WriteLine($"Numbers: {numberString}"); // 1-2-3-4-5
// Join with no separator
string noSep = string.Join("", new[] { "A", "B", "C" });
Console.WriteLine($"No separator: {noSep}"); // ABC
// Join with LINQ transformation
List<Person> people = new List<Person>
{
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
};
string peopleNames = string.Join(", ", people.Select(p => p.Name));
Console.WriteLine($"People: {peopleNames}");
// Join with formatting
string formatted = string.Join(" | ", people.Select(p => $"{p.Name} ({p.Age})"));
Console.WriteLine($"Formatted: {formatted}");
// Join part of a collection
string[] colors = { "Red", "Green", "Blue", "Yellow", "Purple" };
string firstThree = string.Join(", ", colors.Take(3));
Console.WriteLine($"First three: {firstThree}");
// Multi-line join
string[] lines = { "Line 1", "Line 2", "Line 3" };
string multiLine = string.Join(Environment.NewLine, lines);
Console.WriteLine("Multi-line:");
Console.WriteLine(multiLine);
// Alternative: using + operator (less efficient in loops)
string manual = words[0] + " " + words[1] + " " + words[2];
Console.WriteLine($"\nManual concatenation: {manual}");
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}