O'Reilly logo

Microsoft® Visual Basic® 2010 Developer’s Handbook by Klaus Löffelmann and Sarika Calla Purohit

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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
            Console.WriteLine(item.LastName)
            For Each contact In item.listOfContacts
                With contact
                    Console.WriteLine(.ID & ": " & .LastName & ", " & .FirstName)
                End With
            Next
            Console.WriteLine()
        End With
    Next
End Sub

In this example, the Group By clause ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required