C Sharp: creating a List of objects, adding and removing items, and iterating over the collection - Biz Tech

C Sharp: creating a List of objects, adding and removing items, and iterating over the collection

Listen
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 of Person 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:

  1. Define a Person class with Name and Age properties and a constructor.
  2. Create a List<Person> object.
  3. Add three Person objects to the list using the Add() method.
  4. Iterate over the list using a foreach loop and output the Name and Age properties of each Person object to the console using Console.WriteLine().
  5. Remove the second Person object from the list using the RemoveAt() method and store it in a variable.
  6. Output a message to the console indicating which Person object was removed using Console.WriteLine().
  7. Iterate over the modified list again using a foreach loop and output the Name and Age properties of each Person object to the console using Console.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.