C# List Class
C#

C# List Class

Mishel Shaji
Mishel Shaji

List is a collections of items that can be accessed by an index. In C#, we can search, add, remove, and sort items of a List.

The List is represented by List<T> class which is defined in System.Collections.Generic.

Things to remember

  • All List elements are indexed. The starting index is 0.
  • List elements are not sorted automatically.
  • The difference between array and a List is that an array will have fixed size and the size of a List can change dynamically. This makes List an ideal choice in situations where the exact number of elements are unknown.
  • List<T> is generic. This means that it can store any data, object or even a custom type. But ArrayList, which is the non-generic equivalent of List can store only objects. Each items added to an ArrayList will be internally converted to Objects.
  • A List<T> can hold up to 2 billion elements on 64 bit systems.

List properties

List properties are used to set or get the properties of a list. For example, we can find the total number of elements in a List using the Count property.

Property Description
Count Returns the total number of elements.
Items Gets or sets the element at the specified index

List methods

C# offers several methods to help us to work with Lists.

METHOD USAGE
Add Adds an item to the end of a list.
AddRange Appends the elements of a specified collection to the list.
BinarySearch Performs a binary search and returns index of the element.
Clear Clears the list (Removes all elements).
Contains Checks whether the speciied element exists or not in a List.
Insert Inserts an element at the specified index.
Remove Removes the first occurence of a element.
RemoveAt Removes element at the specified position.
Sort Sorts the list elements.

Create a List

We can create Lists that can hold any data and even custom types. First. make sure that you have added reference to System.Collections.Generic namespace.

// Creates a List to store integers
List<int> li = new List<int>();

// Creates a List to store chars
List<char> lc = new List<char>();

// Creates a List to store strings
List<string> ls = new List<string>();

Add elements to a List

To add items to a List, we can use Add() method. This method takes a List item as the first parameter and appends it to the List.

// Creates a List to store integers
List<int> li = new List<int>();

// Add items to the list
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
li.Add(5);

Or we can directly add items to a list as follows:

// Creates a List to store integers
List<int> li = new List<int>() {1, 2, 3, 4, 5};

Or use Insert() method.

List<int> li = new List<int>() {1, 2, 3, 4, 5};

// Insert 5 at the third index
l.Insert(3, 5)

Access list items

List items can be accessed by using:

  • Index
  • for loop
  • foreach loop

Here's an example.

// Creates a List to store integers
List<int> li = new List<int>() {1, 2, 3, 4, 5};

// Access list items using index
Console.WriteLine(li[0]); // Output: 1

// Using for loop
int len = li.Count;
for(int i =0; i < len; i++)
{
	Console.WriteLine("Element at index {0} is {1}", i, li[i]);
}

// Using foreach loop
foreach(var item in li)
{
	Console.WriteLine("List item is {0}", item);
}

Remove list items

To remove items from a List, we can either use Remove() method or RemoveAt() method.

List<int> l = new List<int>() { 1, 2, 3, 4, 5};

// Removes 1 from the list
l.Remove(1);

// Removes second element from the list
l.RemoveAt(1); 

AddRange() method

This method adds elements of a specified collection to the end of the list.

List<int> l = new List<int>() { 1, 2, 3, 4, 5};
List<int> l1 = new List<int>() { 55, 66 };

l1.AddRange(l);
foreach(int i in l1)
{
	Console.WriteLine(i);
}

TrueForAll() method

The TrueForAll() is a method returns true if the specified condition is evaluated to true, otherwise false. Here, the condition can be specified as the predicate type deligate or the lambda expression.

List<int> l = new List<int>() { 2, 4, 6};
bool isEven = l.TrueForAll(i => i % 2 == 0);

if (isEven)
	Console.WriteLine("All numbers are even");
else
	Console.WriteLine("Some numbers are not even");

Object List

A List<T> can also hold objects of any class. Here's an example for a Lit that holds objects of a class Employee.

Employee class

class Employee
{
	public string id { get; set; }
	public string name { get; set; }
	public int salary { get; set; }
}

Employee list

// Create a list to store Employee details
List<Employee> employees = new List<Employee>();

// Create a new employee
Employee e1 = new Employee();
e1.id = "01A";
e1.name = "John Doe";
e1.salary = 50000;

// Add employee to the list
employees.Add(e1);

// Access employee details from the list
Console.WriteLine("Salary of {0} is {1}", employees[0].id, employees[0].salary);

Following this method can become difficult with the increasing number of objects. Therefore, we can initialize List with objects instead of adding them one by one.

See the code below.

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Employee
    {
        public string id { get; set; }
        public string name { get; set; }
        public int salary { get; set; }
    }
    class Program
    {
        static void Main()
        {

            List<Employee> employees = new List<Employee>()
            {
                new Employee(){ id = "01A", name = "John", salary=20000},
                new Employee(){ id = "02A", name = "Jane", salary=25000},
                new Employee(){ id = "01B", name = "Joe", salary=28000}
            };

            //Access List Elements
            foreach(Employee emp in employees)
            {
                Console.WriteLine("Name: {0}, ID: {1}, Salary: {2}", emp.id, emp.name, emp.salary);
            }
        }
    }  

This code, when executed will produce the following output.

Name: 01A, ID: John, Salary: 20000
Name: 02A, ID: Jane, Salary: 25000
Name: 01B, ID: Joe, Salary: 28000
Press any key to continue . . .