using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<Person> people = new List<Person>(); people.Add(new Person("John", 30)); people.Add(new Person("Jane", 25)); people.Add(new Person("Bob", 35)); foreach (Person person in people) { Console.WriteLine(person.Name + " is " + person.Age + " years old."); } Person removedPerson = people[1]; people.RemoveAt(1); Console.WriteLine("Removed " + removedPerson.Name + " from the list."); foreach (Person person in people) { Console.WriteLine(person.Name + " is " + person.Age + " years old."); } } } class Person { public string Name { get; set; } public int Age { get; set; } public Person(string name, int age) { Name = name; Age = age; } }This example creates a
List
ofPerson
objects, adds three items to the list, iterates over the list, removes the second item from the list, and iterates over the modified list again. The following steps are performed:
- Define a
Person
class withName
andAge
properties and a constructor.- Create a
List<Person>
object.- Add three
Person
objects to the list using theAdd()
method.- Iterate over the list using a
foreach
loop and output theName
andAge
properties of eachPerson
object to the console usingConsole.WriteLine()
.- Remove the second
Person
object from the list using theRemoveAt()
method and store it in a variable.- Output a message to the console indicating which
Person
object was removed usingConsole.WriteLine()
.- Iterate over the modified list again using a
foreach
loop and output theName
andAge
properties of eachPerson
object to the console usingConsole.WriteLine()
.Note that there are many other collection types and operations you can perform, such as
Dictionary
,Queue
,Stack
, and sorting. This example is just one possible multi-step process for working with collections.