LINQ Cookbook, Recipe 5: Concatenating the selected strings from a CheckedListBox (Kit George)


          Visual Studio 2008 (Beta2 or Higher)


Categories: LINQ-To-Objects, LINQ and WinForms



  • Open Visual Studio 2008, and Click ‘File/New Project’. Create a new Windows Forms Application project
  • From the toolbox, drag a CheckedListBox to the main form, and a button. Ensure the listbox is large enough to view multiple items
  • DoubleClick the form to creat the load event. Add this code to the load event (this simply populates the CheckedListBox with entries)

CheckedListBox1.Items.AddRange( _

  New String() {“Apple”, “Orange”, “Banana”, _

  “Avocado”, “Tomato”, “Tamarillo”, _

  “Kiwifruit”, “Cherry”})


  • Create the click event for the button (in the code editors dropdowns, in the left drop down, select Button1) and add this code

    MsgBox( _

      Aggregate Box In CheckedListBox1.CheckedItems _

      Into Concat())

    • At the very bottom of the code (after End Class) add this code. This code creates the aggregate ‘Concat’ function which enables this code to be used on the ‘Into’ above 

    Public Module AggregateModule

      <Extension()> Public Function Concat(Of Type)( _

            ByVal ie As IEnumerable(Of Type)) As String

        Dim str As String = “”

        For Each item In ie

        If str <> “” Then str &= “,”

          str &= item.ToString()


        Return str

      End Function

    End Module

    • Alternatively, change the code in the button to be the following and remove the function we created (this is less code, but if you’re going to use this code a lot, then writing the Concat function is preferred) 

    MsgBox((From c In _

            CheckedListBox1.CheckedItems).Aggregate( _

       Function(ByVal x, ByVal y) x + “,” + y))