C# List

In C#, a list is a collection that can dynamically grow or shrink in size as items are added or removed. There are two primary types of lists in C#

  1. Generic Lists
  2. Non-Generic Lists.

1. Generic List (List<T>)

A generic list is a type-safe collection that allows you to store elements of a specific type. The type of elements is defined at compile time using the List class from the System.Collections.Generic namespace, where T represents the type of elements stored in the list.

Important Features

1. Type-safe: You specify the type of the list elements at compile time, which ensures that only elements of that type can be added to the list.

2. Dynamic resizing: The list automatically resizes as you add or remove elements.

3. Provides various methods for adding, removing, searching, and sorting elements.

How to Declare and Initialize a Generic List?

You have to use a List<T>, you must include the System.Collections.Generic namespace.

Example: Use List type int


using System;
using System.Collections.Generic;

List myNumbers = new List(); // A list of integers
myNumbers.Add(5);  // Adding an element to the list
myNumbers.Add(10);
myNumbers.Add(15);

Console.WriteLine(myNumbers[1]); // Accessing the second element (Output: 10)
Console.WriteLine(myNumbers.Count); // Output: 3 (Number of elements in the list)

Example: Use List type string


using System;
using System.Collections.Generic;

List employeeNames = new List{"John", "Tom", "Mark"}; // A list of string
employeeNames.Add("John");  // Adding an element to the list
employeeNames.Add("Tom");
employeeNames.Add("Mark");

Console.WriteLine(employeeNames[0]); // Accessing the second element (Output: John)
Console.WriteLine(employeeNames.Count); // Output: 3 (Number of elements in the list)

Remove Method from the Generic List


using System;
using System.Collections.Generic;

List employeeNames = new List{"John", "Tom", "Mark"}; // A list of string
employeeNames.Remove("John");  // Remove John element from the list
Console.WriteLine(employeeNames[0]); // Accessing the element (Output: Tom)
Console.WriteLine(employeeNames.Count); // Output: 2 (Number of elements in the list)

Search Item from the Generic List through Contains()


using System;
using System.Collections.Generic;

 List employeeNames = new List{"John", "Tom", "Mark"}; // A list of string
    if(employeeNames.Contains("John")) {
       Console.WriteLine("John is in the List");
    }  

Explanation: We find John through Contains() method from the List.

Sort the Generic List Item


using System;
using System.Collections.Generic;

List employeeNames = new List{"John", "Tom", "Mark"}; // A list of string
employeeNames.Sort();
foreach (string empName in employeeNames)
{
  Console.WriteLine(empName);  // Output: John, Mark, Tom
}

Clear the all elements from the List


using System;
using System.Collections.Generic;

List employeeNames = new List{"John", "Tom", "Mark"}; // A list of string
 employeeNames.Clear();
 foreach (string empName in employeeNames)
  {
          Console.WriteLine(empName[0]);  // Output: 
  }

Generic List with Custom Types

You can also create generic lists of custom objects. For example, if you have a Employee class:


using System;
using System.Collections.Generic;

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Employee(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class MyProgram
{
    static void Main()
    {
        List employee = new List();

        employee.Add(new Employee("John", 35));
        employee.Add(new Employee("Tom", 30));
        employee.Add(new Employee("Mark", 25));

        // Access elements
        Console.WriteLine(employee[0].Name); // Output: John
        Console.WriteLine(employee[0].Age);  // Output: 35

        // Looping through the list
        foreach (var emp in employee)
        {
            Console.WriteLine($"{emp.Name} is {emp.Age} years old.");
        }
    }
}

Non-Generic Lists (ArrayList):

A non-generic list is an older type of list that can hold items of any type. It is part of the System.Collections namespace and stores objects of type object, so it can hold elements of different types (e.g., integers, strings, custom objects) in the same list.

Important Features

1. Not type-safe: Since it stores object types, you can add any type of element, but this also means that you lose compile-time type safety.

2. Performance Overhead: Every time you add an element, it has to box the value if it’s a value type (e.g., int), which can be less efficient than using a generic list.

3. Dynamic resizing: Like generic lists, non-generic lists can dynamically resize as elements are added or removed.

Example:


using System;
using System.Collections;

ArrayList list = new ArrayList(); // Create an ArrayList
 // Add elements
list.Add(20);  // Adds an integer
list.Add("John");  // Adds a string
// Accessing elements (Note: Requires type casting)
Console.WriteLine((int)list[0]); // Output: 10
Console.WriteLine((string)list[1]); // Output: John

Non-Generic List with Custom Types

When adding custom types to a non-generic list, you need to cast them to the correct type when retrieving them.

Example:


using System;
using System.Collections;

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Employee(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Program
{
    static void Main()
    {
        ArrayList list = new ArrayList();

        list.Add(new Employee("John", 35));
        list.Add(new Employee("Tom", 30));

        // Accessing custom objects (requires casting)
        Employee emp1 = (Employee)list[0];
        Employee emp2 = (Employee)list[1];

        Console.WriteLine(emp1.Name); // Output: John
        Console.WriteLine(emp2.Age);  // Output: 30
    }
}