Grouping Collections

The Group By clause lets you group duplicates of items or multiple collections. Suppose that you want to group a contact list by last names. Later, in a nested loop, you want to iterate through the names and the contacts assigned to the names. You can do this with the Group By clause, as shown in the following example:

Sub GroupByDemo()
    Dim resultList = From adrElement In adrList
                        Group By adrElement.LastName Into listOfContacts = Group
                        Order By LastName

    For Each item In resultList
        With item
            For Each contact In item.listOfContacts
                With contact
                    Console.WriteLine(.ID & ": " & .LastName & ", " & .FirstName)
                End With
        End With
End Sub

In this example, the Group By clause ...

Get Microsoft® Visual Basic® 2010 Developer’s Handbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.