An Introduction to C# List

The C# List <T> is the part of System.Collection.Generic Namespace that represents a strongly typed list of objects.
List lst_num_Ins = new List();
  • The List is just like the ArrayList except the later is non-generic.
  • The arrays are fixed size while List <T> can grow as needed automatically.
  • Other generic classes in the System.Collection.Generic Namespace includes Dictionary, Queue, and Stack.
  • A list is created by using the new keyword as shown in the example in the next section.
  • The index of the list starts at 0.
  • You may use Add method of the List class to add new elements at the end of a list.
lst_numbers.Add(1);
lst_numbers.Add(3);
lst_numbers.Add(5);
  • For removing all elements from the list, you may use the Clear method.
List_name.Clear()
  • For adding a new element at the specified position, use the Insert method of the List class.
lst_numbers.Insert(3, 13);
  • For removing a specified element from the list, use the Remove method.
  • To sort a list, the List class has the Sort method.
  • The section below explains how to create, initialize, and iterate through lists. You may also see examples of a few useful list methods.

How to create/declare a List<T> in C#?

The syntax for creating a List<T>:

List<int> list_name = new List<int>();

In the above syntax, we created a list namely list_name of the type int. Similarly, you may create a list of string as follows:

List<string> list_string = new List<string>();
Did you know? The term “Generic” means allowing to design of a class or method where its type is specified at the declaration/initialization time. The Generics were added in the C# language version 2.0.

Initializing a list

You may use the add method of the list class to add new elements to the list after its declaration. However, you may also create elements at the time of declaration in the list.

For example, we have a List of type string with three elements at the time of declaration as follows:

List<string> str_list = new List<string>(new string[] { “string1”, “string2”, “string3” });

The following simple code shows declaring, initializing, and accessing a list element:

using System;

using System.Collections.Generic;

class List_Demos

{
    static void Main()
    {
        List<string> str_list = new List<string>(new string[] { "string1", "string2", "string3" });

        System.Console.WriteLine(str_list[1]);
        Console.ReadLine();
    }
}

The output of the above example should be:

String2

As such, the index of a list starts at zero.

Note the System.Collections.Generic; as the second line of code. You have to include this to work with Lists.

Adding elements to a list by Add method

In the example of the List Add method, I have created a list of int type. This is followed by using the Add method for adding five elements to the list.

The Add method inserts a new element at the end of List <T>.

Finally, I used the foreach statement for iterating through the list and displayed the List<T> elements:

using System;

using System.Collections.Generic;

class List_Demos

{
    static void Main()
    {
        List<int> lst_numbers = new List<int>();

        lst_numbers.Add(1);
        lst_numbers.Add(3);
        lst_numbers.Add(5);
        lst_numbers.Add(7);
        lst_numbers.Add(9);

        foreach (int num in lst_numbers)
        {
            System.Console.WriteLine("The List element = " +num);
        }
        Console.ReadLine();
    }
}

The output:

c# list

How to insert an item at the specified index by the Insert method

Rather than adding an element at the end of a List<T> you may add an element at the specified index. For that, you may use the Insert method of the List<T> class.

The general syntax of using the Insert method is:

public void Insert (int index, T item);

In this example, a List<T> of int items is created initially with five elements. Then a foreach statement is used to display the List<T>.

This is followed by using the Insert method and I added a new element at the 3 index (starting at 0).

Again, I used the foreach and displayed the list elements and you can see the order of new element:

using System;

using System.Collections.Generic;
class List_Insert_Demo

{
    static void Main()
    {

        List<int> lst_num_Ins = new List<int>();

        lst_num_Ins.Add(1);
        lst_num_Ins.Add(3);
        lst_num_Ins.Add(5);
        lst_num_Ins.Add(7);
        lst_num_Ins.Add(9);

        System.Console.WriteLine("List before Insert method");
        foreach (int num in lst_num_Ins)
        {
            System.Console.WriteLine(num);
        }
        lst_num_Ins.Insert(3, 13);

        System.Console.WriteLine("List after Insert method");
        foreach (int num in lst_num_Ins)
        {
            System.Console.WriteLine(num);
        }
        Console.ReadLine();
    }
}

c# list-insert

The number 13 is displayed at 3 index.

The example of adding multiple items by InsertRange method

If you have several elements to add from another collection to an existing list then you may use the InsertRange method.

The syntax for using the InsertRange method is:

public void InsertRange (int index, System.Collections.Generic.IEnumerable<T> collection);

So, you may specify the index position where you want to start inserting new elements from another collection.

To demonstrate that, the following example creates a list and an array. After creating the array, its elements are added to the list as shown in the example below:

using System;

using System.Collections.Generic;
class List_InsertRange_Demo

{

    static void Main()

    {
        List<string> lst_str = new List<string>();
        lst_str.Add("This");
        lst_str.Add("is");
        lst_str.Add("list");
        lst_str.Add("Items");

        System.Console.WriteLine("************Before InsertRange**********");

        foreach (string val in lst_str)
        {
            System.Console.WriteLine(val);
        }

    //Declaring and initializing an array

        string[] Arr_in_lst = new string[] { "The", "Array", "Elements"};

    //Using InsertRange method

        lst_str.InsertRange(2, Arr_in_lst);

        System.Console.WriteLine("*************After InsertRange***********");

        foreach (string val2 in lst_str)
        {
            System.Console.WriteLine(val2);
        }

        Console.ReadLine();
    }
}

The output of the above program:

c# list insertRange

An example of sorting a List<T> by the sort method

If you have a list of which items are in random order and you want it to sort then use the List<T> class sort() method.

For using the sort method, simply use the list name that you want to sort followed by the sort() keyword.

In the following example, we have a random list of integer elements. The list items are displayed before and after using the sort() method.

Have a look at the code and output:

using System;

using System.Collections.Generic;
class List_Sort_Demo

{

    static void Main()
    {
        List<int> lst_num_sort = new List<int>();

        lst_num_sort.Add(11);
        lst_num_sort.Add(31);
        lst_num_sort.Add(5);
        lst_num_sort.Add(7);
        lst_num_sort.Add(9);
        lst_num_sort.Add(15);
        lst_num_sort.Add(1);
        lst_num_sort.Add(3);

        System.Console.WriteLine("*************Before Sorting***********");

        foreach (int num in lst_num_sort)
        {
            System.Console.WriteLine(num);
        }
        lst_num_sort.Sort();

        System.Console.WriteLine("\n" + "*************After Sorting***********" + "\n");
        foreach (int num in lst_num_sort)
        {
            System.Console.WriteLine(num);
        }
        Console.ReadLine();
   }
}

The result:

c# list-sort

How to remove a List<T> item? The Remove method

The Remove() method deletes the first occurrence of the specified object from the List<T>.

The syntax of using the Remove method is:

public bool Remove (T item);

If the item is found, the Remove method returns true, otherwise false.

See the following example where we have a list of following numbers:

[1, 5, 11, 21, 5, 15]

The Remove() method is used to delete the element 5 from the list. See the code and result:

using System;

using System.Collections.Generic;
class List_Remove_Demo

{
    static void Main()
    {

        List<int> lst_Remove = new List<int>();
        lst_Remove.Add(1);
        lst_Remove.Add(5);
        lst_Remove.Add(11);
        lst_Remove.Add(21);
        lst_Remove.Add(5);
        lst_Remove.Add(15);

        System.Console.WriteLine("*************List Before Remove***********");

        foreach (int num in lst_Remove)
        {
            System.Console.WriteLine(num);
        }
        lst_Remove.Remove(5);

        System.Console.WriteLine("\n" + "*************List After Remove***********" + "\n");
        foreach (int num in lst_Remove)
        {
            System.Console.WriteLine(num);
        }

       Console.ReadLine();
    }
}

The Result:

c# list Remove

You can see, the List<T> contains 5 two times. However, the Remove() method deleted only the first occurrence.

Removing all occurrences of the specified element by RemoveAll method

  • The example below shows using the RemoveAll method for deleting all occurrences of the item in the specified List<T>.
  • I am using the same list items as in the above example i.e. occurrences of item 5 two times.
  • See the output before and after using the RemoveAll method:
using System;

using System.Collections.Generic;
class List_RemoveAll_Demo

{
    static void Main()
    {

        List<int> lst_RemoveAll = new List<int>();
        lst_RemoveAll.Add(1);
        lst_RemoveAll.Add(5);
        lst_RemoveAll.Add(11);
        lst_RemoveAll.Add(21);
        lst_RemoveAll.Add(5);
        lst_RemoveAll.Add(15);

        System.Console.WriteLine("*************List Before RemoveAll***********");
        foreach (int num in lst_RemoveAll)
        {
            System.Console.WriteLine(num);
        }

        lst_RemoveAll.RemoveAll(item => item == 5);


        System.Console.WriteLine("\n" + "*************List After RemoveAll***********" + "\n");
        foreach (int num in lst_RemoveAll)
        {
            System.Console.WriteLine(num);
        }

        Console.ReadLine();
    }
}

The Output:

c# list-RemoveAll

The output shows the occurrence of 5 is removed twice.

Using Clear method for removing all elements in a List<T>

If you require removing all elements from the list in a single call then use the Clear() method.

The Clear() method is simple to use i.e.:

List_name.Clear()

The example below shows a list before and after using the clear method:

using System;

using System.Collections.Generic;

class List_Clear_Demo

{

    static void Main()

    {
        List<int> lst_Clear = new List<int>();
        lst_Clear.Add(100);
        lst_Clear.Add(500);
        lst_Clear.Add(1100);

        System.Console.WriteLine("*************List Before Clear***********");

        foreach (int num in lst_Clear)
        {
            System.Console.WriteLine(num);
        }

        lst_Clear.Clear();
        System.Console.WriteLine("\n" + "*************List After Clear***********" + "\n");
        foreach (int num in lst_Clear)
        {
            System.Console.WriteLine(num);
        }

       Console.ReadLine();
    }
}

c# list-Clear

You can see the list is empty after using the Clear() method.

How to search in C# List<T>?

For searching element(s) in lists, you may use several methods. The following methods are available in C#:

  • Contains
  • Find
  • Exists

Each of these methods is explained below with an example.

The example of Contains method

The Contains method is used to determine if an item exists in the list or not. It returns true if the item exists and false if it does not.

The following simple example shows how to use the Contains method:

using System;

using System.Collections.Generic;

class List_Contains

{
    static void Main()
    {
        List<string> lst_demo = new List<string>();
        lst_demo.Add("C#");
        lst_demo.Add("C Sharp");
        lst_demo.Add("Tutorials");

        if (lst_demo.Contains("Tutorials"))
        {
            System.Console.WriteLine("The item Tutorials exists in the List<T>");
        }
        else {
            System.Console.WriteLine("The item Tutorials does not exist in the List<T>");
        }

        Console.ReadLine();
    }
}

The output of the above code is:

The item Tutorials exists in the List<T>
Note that the Contains method performs searching as case sensitive. If we used the word “tutorials” the returned value should have been false.

How to use Find method of List<T>?

The general syntax for using the Find method:

public T Find (Predicate<T> match);

By using the Find method, you may search a list for items based on the condition that is defined by the specified predicate.

The Find method returns the first occurrence in the entire List<T>.

To show how it works, see the example below.

We have a string list of six items. The fruit “Mango” is used two times in the List<T>. See how the Find method is used with lambda expression and the result:

using System;

using System.Collections.Generic;
class List_Find

{

    static void Main()
    {
        List<string> lst_Find = new List<string>();
        lst_Find.Add("Mango");
        lst_Find.Add("Apple");
        lst_Find.Add("Banana");
        lst_Find.Add("Pine Apple");
        lst_Find.Add("Strawberry");
        lst_Find.Add("Apple");

        string str_result = lst_Find.Find(X => X == "Mango");
        System.Console.WriteLine(str_result);
        Console.ReadLine();
    }
}

The result:

Mango

Learn more about the Find method here.

Using Exists method for searching element(s) in List<T>

You may also use the Exists method for determining if one or more elements exist in the List<T> by giving the condition defined by the specified predicate.

The general syntax for using the Exists method is:

public bool Exists (Predicate<T> match);

The following example shows using the Exists method:

using System;

using System.Collections.Generic;
class List_Find

{

    static void Main()

    {
        List<int> lst_Exists = new List<int>();
        lst_Exists.Add(1);
        lst_Exists.Add(3);
        lst_Exists.Add(5);
        lst_Exists.Add(7);
        lst_Exists.Add(9);

        bool bool_result1 = lst_Exists.Exists(X => X > 10 );
        bool bool_result2 = lst_Exists.Exists(X => X < 10);

        System.Console.WriteLine(bool_result1);
        System.Console.WriteLine(bool_result2);
        Console.ReadLine();
    }
}

The output of the code:

False

True

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!