In the past I described how to perform string aggregates in T-SQL. In this post I will show how strings can be concatenated in LINQ.
I am using ADO.NET data table as a source for the query, but LINQ being LINQ can pull data pretty much from anything so this example can easily be adjusted.
First things first, let’s create the source. As in T-SQL post I am using ol’ faithful Northwind database and getting data from the Employees table:
Dim oConn As New SqlConnection(sMyConnStr) : oConn.Open() Dim oComm As New SqlCommand("SELECT Country, FirstName FROM Employees ORDER BY Country, FirstName", oConn) Dim oAd As New SqlDataAdapter(oComm) : Dim oTable As New DataTable : oAd.Fill(oTable)
This will fill the datatable with employees’ first names and countries
Country FirstName UK Anne UK Michael UK Robert UK Steven USA Andrew USA Janet USA Laura USA Margaret USA Nancy
And now we want to group this by the country, combining first names into comma separated string. Continue reading →