In this blog post, we will learn how we can join an array in C#.
Joining an array means joining the values of the array using a delimiter.
When we join an array in C#, we loop through all the values and insert a delimiter value (if any) to join and make the result.
Example, an array ["John", "Julie", "Sameer"] would be joined to make a string "John,Julie,Sameer" if the delimiter was a comma value.
How do we achieve this? In C#, we use the Join() method that is available to us in the sealed class String.
public static string Join(string separator, params obj[] array)
Looking at the syntax of the Join method above, we can see that it takes in two parameters, the first parameter is the separator (or delimiter) and the second parameter is the array of values that needs to be joined.
Code example:
// Creating a string array with some values var arrayOfNames = new string[] { "John", "Julie", "Sameer" }; // Using the string.Join(separator, array) method // to join the values of the array var joinedResult = string.Join(", ", arrayOfNames); // Writing to the console to see the result Console.WriteLine(joinedResult);
Output:
John, Julie, Sameer