Imports System
Imports System.Collections.Generic
Imports System.Linq
' ------------------------------------------------------------
' Example: Sorting a list of classes that contain nested classes
' ------------------------------------------------------------
' A nested class representing an address
Public Class Address
Public Property City As String
Public Property Zip As Integer
End Class
' A class representing a person, containing a nested Address
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Address As Address
End Class
Module Program
' ------------------------------------------------------------
' Helper function to print the list
' ------------------------------------------------------------
Sub PrintPersons(people As IEnumerable(Of Person))
For Each p In people
Console.WriteLine($"{p.Name} | age: {p.Age} | city: {p.Address.City} | zip: {p.Address.Zip}")
Next
End Sub
' ------------------------------------------------------------
' Main program
' ------------------------------------------------------------
Sub Main()
' Create a sample list of people
Dim people As New List(Of Person) From {
New Person With {.Name = "Alice", .Age = 30, .Address = New Address With {.City = "San Francisco", .Zip = 42100}},
New Person With {.Name = "Bob", .Age = 40, .Address = New Address With {.City = "Austin", .Zip = 32000}},
New Person With {.Name = "Carol", .Age = 35, .Address = New Address With {.City = "New York City", .Zip = 42000}},
New Person With {.Name = "Dave", .Age = 25, .Address = New Address With {.City = "Austin", .Zip = 32000}},
New Person With {.Name = "Eve", .Age = 28, .Address = New Address With {.City = "New York City", .Zip = 61000}}
}
' ------------------------------------------------------------
' Sort using LINQ:
' 1. Order by city
' 2. Then by zip
' 3. Then by age
' This naturally accesses nested fields and keeps the code clear.
' ------------------------------------------------------------
Dim sorted =
people _
.OrderBy(Function(p) p.Address.City) _
.ThenBy(Function(p) p.Address.Zip) _
.ThenBy(Function(p) p.Age)
' Print the sorted result
PrintPersons(sorted)
End Sub
End Module
' run:
'
' Dave | age: 25 | city: Austin | zip: 32000
' Bob | age: 40 | city: Austin | zip: 32000
' Carol | age: 35 | city: New York City | zip: 42000
' Eve | age: 28 | city: New York City | zip: 61000
' Alice | age: 30 | city: San Francisco | zip: 42100
'