using System;
using System.Collections.Generic;
using System.Linq;
// ------------------------------------------------------------
// Example: Sorting a list of user-defined structs
// that contain nested structs
// ------------------------------------------------------------
// A nested struct representing an address
public struct Address
{
public string City;
public int Zip;
}
// A struct representing a person, containing a nested Address
public struct Person
{
public string Name;
public int Age;
public Address Address;
}
public class Program
{
// ------------------------------------------------------------
// Helper function to print the list
// ------------------------------------------------------------
static void PrintPersons(IEnumerable<Person> people)
{
foreach (var p in people) {
Console.WriteLine($"{p.Name} | age: {p.Age} | city: {p.Address.City} | zip: {p.Address.Zip}");
}
}
// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
public static void Main()
{
// Create a sample list of people
var people = new List<Person>
{
new Person { Name = "Alice", Age = 30,
Address = new Address { City = "San Francisco", Zip = 42100 } },
new Person { Name = "Bob", Age = 40,
Address = new Address { City = "Austin", Zip = 32000 } },
new Person { Name = "Carol", Age = 35,
Address = new Address { City = "New York City", Zip = 42000 } },
new Person { Name = "Dave", Age = 25,
Address = new Address { City = "Austin", Zip = 32000 } },
new Person { Name = "Eve", Age = 28,
Address = new Address { City = "New York City", Zip = 61000 } }
};
// ------------------------------------------------------------
// Sort using LINQ:
// 1. Order by city
// 2. Then by zip
// 3. Then by age
// ------------------------------------------------------------
var sorted =
people
.OrderBy(p => p.Address.City)
.ThenBy(p => p.Address.Zip)
.ThenBy(p => p.Age);
// Print the sorted result
PrintPersons(sorted);
}
}
/*
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
*/