A list is a generic collection of items that can be accessed by index. You can access, search, sort, or manipulate the list items just like you can do with an Array.

What is a list in C#

The List is a class in the System.Collections.Generic namespace. It is a generic class that any type of data can be stored in it. Before you can use the list class in your program, you need to import the System.Collections.Generic namespace as follows:

using System.Collections.Generic;

Creating a List in C#

The list is a generic type so that you can create a list of any data type, such as integer, string, etc. Or a reference type such as Books, Cars, etc.

    List<int> list = new List<int>();
    List<string> list = new List<string>();
    List<Object> list = new List<object>();
    List<Cars> customers = new List<Cars>();

Creating a list of integers

To create an empty list, use the following two methods:
Method 1:

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

Method 2:

    var list = new List<int>();

Creating a list and initializes it with some integer values.

var list = new List<int>() { 1, 2, 3};

To access any item of the list, you have to use its index, such as list[1], will return the item being at 2nd place as the list has a zero-based index.

Note: An Index out of range exception (IndexOutOfRangeException) will be thrown if you try to access an index outside of the range of the list.

Inserting item in the list

Lets’ say we have a list with three integers define upon declaration. To add another integer at the end of the list, use:

list.Add(4);

This will add the number 10 to the end of the list.

Inserting list values inside another list

To add items from another list to the end of list use:

    List<int> list1 = new List<int>() { 1, 2, 3 };
    List<int> list2 = new List<int>() { 4, 5 };
    list2.AddRange(list2);

Now list1 contains the items: 1,2,3,4,5

To search through the list

You can perform the binary search on the list. If the element you are looking for is found, it will return the zero-based index of the item of the list. Else it will return a negative number.

    List<int> list = new List<int>() { 1, 2, 3 };
    int index = list.BinarySearch(2);

To overload specified comparer use:

    int index = list.BinarySearch(item: 2, comparer: new CustomComparer());

To overload the specified comparer and search only in a limited range, use:

    int index = list.BinarySearch(index: 1, count: 3, item: 4, comparer: new CustomComparer());

In case, the search didn’t find the required element in the list; it will return the negative number as follows.

int index = list.BinarySearch(index: 1, count: 2, item: 4, comparer: new CustomComparer());

Now the code of the class customComparer

    public class CustomComparer : IComparer<int>
    {
        public int Compare(int a, int b) { return a.CompareTo(b); }
    }

Clear the list

To remove all the items from the list, use the following.

list.Clear();

Search for a specific item

The following method returns true if the given item exists in the list, false otherwise.

    bool found = list.Contains(2);

Copy list into an array

The following code will copy all list items into the beginning of the specified array.

list.copyto(array);

To copy all list, starting from index # 2

list.CopyTo(array, arrayIndex: 2);

To copy a range of items from the list

list.CopyTo(index: 1,array: array, arrayIndex: 2,count: 1);

Check a specific predicate on list

The following method returns true if the list contains the item that matches with a specified predicate, false otherwise.

The code below will return true if all the items in the list are equal or greater than 3.

    bool found = list.Exists(x => x >= 3);

Change the type of items of the list

To covert items using a specified delegate, use:

    var list1 = new List<int>() { 1, 2, 3, 4, 5 };
    var converter = new Converter<int, decimal>(x => x);
    var list2 = list1.ConvertAll<decimal>(converter);

Now list2 contains: 1.0, 2.0, 3.0, 4.0, 5.0

Check if two lists are equal

The following code returns true as the two lists below to the same instance.

    var list1 = new List<int>() { 1, 2, 3, 4 };
    var list2 = list1; // Assigning list1 to list2
    bool result = list1.Equals(list2);

And this will return false.

    var list1 = new List<int>() { 1, 2, 3, 4 };
    var listB = new List<int>() { 1, 2, 3, 4 }; // creating a new instance for list2
    bool result = list1.Equals(list2);

Find the item in a List

The following code will the first occurrence of the item matching the specified predicate.

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    int item = list.Find(x => x > 1);

Find all items matching the predicate

    List<int> listA = new List<int>();
    List<int> listB= listA.FindAll(x => x > 2);

Returns an empty list, if no item matches the predicate being specified.

    List<int> listA = new List<int>();
    List<int> listB = listA.FindAll(x => x > 10);

Returns the index of the matched item

To returns the index of the first item which matches the predicated. You can also give the starting index as the parameter of the list.FindIndex method.
It searches the list for the item in the range specified by startIndex and count variables.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int index = list.FindIndex(x => x < 5);
    Console.WriteLine(index);

    int index = list.FindIndex(startIndex: 2, match: x => x < 5);
    Console.WriteLine(index);

    int index = list.FindIndex(startIndex: 2, count: 2, match: x => x < 5);
    Console.WriteLine(index);

    int index = list.FindIndex(startIndex: 2, count: 2, match: x => x < 3);
    Console.WriteLine(index);

Find the last item in a List

To find the last occurrence of the item being matched, use:

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int item = list.FindLast(x => x < 5);
    Console.WriteLine(item);

    int item = list.FindLast(x => x > 10);
    Console.WriteLine(item);

Returns the index of the last occurrence of the item (specified predictor)

It returns the previous occurrence of the matching items from the list. You can also set the range and starting point for the search in the parameter of the list.FindlastIndex method.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int index = list.FindLastIndex(x => x < 2);
    Console.WriteLine(index);

    int index = list.FindLastIndex(startIndex: 2, match: x => x < 4);
    Console.WriteLine(index);

    int index = list.FindLastIndex(startIndex: 2, count: 2, match: x => x < 3);
    Console.WriteLine(index);

    int index = list.FindLastIndex(startIndex: 2, count: 2, match: x => x < 4);
    Console.WriteLine(index);

Returns the index of the last occurrence of the item found in the list

It returns the zero-based index of the previous occurrence of the item being found in the list. It returns -1 if the item isn’t found in the list.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int index = list.LastIndexOf(5);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 5, index: 2);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 5, index: 2, count: 2);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 5, index: 2, count: 1);
    Console.WriteLine(index);

Returns the index of item

It searches for the specified item in the list. You can give the starting index and the range of the list to search for the item. It returns -1 if the item isn’t found in the range.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int index = list.IndexOf(6);
    Console.WriteLine(index);

    int index = list.IndexOf(item: 6, index: 1);
    Console.WriteLine(index);

    int index = list.IndexOf(item: 6, index: 1, count: 2);
    Console.WriteLine(index);

    int index = list.IndexOf(item: 6, index: 1, count: 2);
    Console.WriteLine(index);

Insert an item in the list at a specified index

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    list.Insert(index: 1, item: 5);

This will insert 5 at index 1.

Insert item of another list

The following code will insert items of another list into the list at the index being specified.

    List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    List<int> list2 = new List<int>() { 21,22,23 };
    list1.InsertRange(index: 1, collection: list2);

Returns the last occurrence of the item

The following code returns the last occurrence of the item of the list within the range (if given).

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int index = list.LastIndexOf(6);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 6, index: 3);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 6, index: 3, count: 2);
    Console.WriteLine(index);

    int index = list.LastIndexOf(item: 6, index: 3, count: 2);
    Console.WriteLine(index);

Remove the first matching item

To remove the first occurrence of the item, use the following:

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    list.Remove(item: 4);

Removing all items from the list

This will remove all items of the list matched with the specified predictor. For example, the following code removes all elements less than 4.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    list.RemoveAll(x => x < 4);

Removing items from the specified range

The following code removes the items from index number 2 and removes 3 items from the list.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    list.RemoveRange(index: 2, count: 3);

Match list with the predicate

TrueForAll() method returns true if all the items in the list match the specified predicate.

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    bool result = list.TrueForAll(x => x < 10);
    Console.WriteLine(result);

    bool result = list.TrueForAll(x => x < 5);
    Console.WriteLine(result);

Reverse the order of the list

To reverse the order of the items in a list, use the Reverse() method.
If you apply the following code on a list containing 1,2,3,4, it will return 4,3,2,1

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.Reverse();

Sorting the list items

To sort all the items in the list use Sort() method.

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.Sort();

Sort list using comparison delegate

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.Sort((x, y) => x.CompareTo(y));

Create a custom sorting flow

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.Sort(new MyComparer());

And the comparer Class

    public class MyComparer : IComparer<int>
    {
        public int Compare(int x, int y) { return x.CompareTo(y); }
    }

Trimming the list capacity

To reduce the memory usage, you can opt to trim the list capacity if it’s reasonable.

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.TrimExcess();

If the count is the same as the capacity, it does nothing.

Copy a list into Array

This code will create a new list and copy it into the array.

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    int[] array = list.ToArray();

Foreach method in C#

This is similar to the standard foreach statement in C# and runs the specified action on each item of the list.
For example, the following code snippet will print all elements of the list.

    List<int> list = new List<int>() { 1, 2, 3, 4 };
    list.ForEach(x => { Console.Write(x); });

Returns a list with a range of items

    List<int> list1 = new List<int>() { 1, 2, 3, 4 };
    var list2 = list1.GetRange(index: 1, count: 2);

Related Articles

Last modified: September 28, 2019

Comments

Write a Reply or Comment

Your email address will not be published.