This program uses advanced LINQ to filter a list of people to only adults, then groups them by their city. It prints each city and the adults living there.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var people = new List<Person>
{
new Person("Alice", 30, "New York"),
new Person("Bob", 17, "Seattle"),
new Person("Charlie", 25, "New York"),
new Person("Diana", 22, "Seattle")
};
// Find adults and group them by city
var adultsByCity = people.Where(p => p.Age >= 18)
.GroupBy(p => p.City);
foreach (var group in adultsByCity)
{
Console.WriteLine($"City: {group.Key}");
foreach (var person in group)
{
Console.WriteLine($" - {person.Name}, Age {person.Age}");
}
}
}
}
class Person
{
public string Name { get; }
public int Age { get; }
public string City { get; }
public Person(string name, int age, string city)
{
Name = name;
Age = age;
City = city;
}
}