Join
This VB.NET function combines many string
elements into a single string
. It acts on an array or List
(we do not need to convert a List
to an array first).
By using the Join
function, we collapse these collections into String
instances. This can help with file handing, or for storage of data in a database.
This program creates an array of 3 strings. Then, we invoke the String.Join
function on this array with the first argument being a string
literal.
string
has the delimiter placed between all the elements—but not at the start or end.Join
requires a delimiter character and a collection of strings. It places this separator in between the strings in the result.Module Module1 Sub Main() ' Three-element array. Dim array(2) As String array(0) = "Dog" array(1) = "Cat" array(2) = "Python" ' Join array. Dim result As String = String.Join(",", array) ' Display result. Console.WriteLine(result) End Sub End ModuleDog,Cat,Python
You can specify the elements you want to join directly inside the String.Join
call. Just pass more than 2 arguments to the String.Join
function.
Module Module1 Sub Main() ' Join array. Dim result As String = String.Join("-", "Dot", "Net", "Perls") ' Display result. Console.WriteLine(result) End Sub End ModuleDot-Net-Perls
You can also join objects together into a single string
. In the VB.NET language, each object can be converted into a String
.
String.Join
function converts each object to a string
and then joins those strings together.Module Module1 Sub Main() ' Join array. Dim result As String = String.Join("/", 1, 2, 3, "VB.NET") ' Display result. Console.WriteLine(result) End Sub End Module1/2/3/VB.NET
Join
List
What should you do if you need to join the elements of a List
? We can just pass the List
directly to Join
. This feature was added in newer versions of .NET.
Module Module1 Sub Main() ' List. Dim list As List(Of String) = New List(Of String) list.Add("Dot") list.Add("Net") list.Add("Perls") ' Join list. Dim result As String = String.Join("*", list) ' Display result. Console.WriteLine(result) End Sub End ModuleDot*Net*Perls
The String.Join
function provides the opposite effect of the Split
function. It takes a collection of elements and combines them into a single string
separated by a delimiter.