C# List (List<T>)

In c#, List is a generic type of collection so it will allow to store only strongly typed objects i.e. an elements of same data type and the size of list will vary dynamically based on our application requirements like adding or removing an elements from the list.

 

In c#, list is same as an arraylist but only difference is arraylist is a non-generic type of collection so it will allow store an elements of different data types.

C# List Declaration

In c#, list is a generic type of collection and it is provided by System.Collections.Generic namespace.

 

As discussed, collection is a class so to define a list, we must need to declare an instance of the list class before we perform any operations like add, delete, etc. like as shown below.

 

List<T> lst = new List<T>();

If you observe above list declaration, we created a generic list (lst) with an instance of list class using type parameter (T) as placeholder with an angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate that the list is a generic type and type parameter (T) is used to represent a type of elements to be accepted by list.

 

In c#, the generic list (List<T>) is an implementation of IList<T> interface so we can also use IList<T> interface to create an object of generic list (List<T>) like as shown below.

 

IList<T> lst = new List<T>();

C# List Initialization

Following is the example of initializing a generic list by specifying a required type to accept values to store.

 

List<string> lst = new List<string>();

If you observe above example, we defined a list (lst) with string data type to store only string elements.

C# List Properties

Following are the some of commonly used properties of generic list in c# programming language.

 

PropertyDescription
Capacity It is used to get or set the number of elements a list can contain.
Count It is used to get the number of elements in list.
Item It is used get or set an element at the specified index.

C# List Methods

Following are the some of commonly used methods of generic list to perform add, search, insert, delete or sort operations in c# programming language.

 

MethodDescription
Add It is used to add an element at the end of the List.
AddRange It is used to add all the elements of specified collection at the end of the List.
Clear It will remove all the elements from the List.
Contains It is used determine whether the specified element exists in the List or not.
CopyTo It is used to copy entire List to compatiable one-dimensional array.
Find It is used to search for an element that matches the conditions defined by the specified predicate and return the first occurrence of the List.
FindAll It is used to retrieve all the elements that matches the conditions defined by the specified predicate.
ForEach It is used to iterate through the List to access an elements.
Insert It is used to insert an element into the List at the specified index.
InsertRange It is used to insert all the elements of specified collection into List starting from the specified index.
Remove It is used to remove the first occurence of specified element from the List.
RemoveAt It is used to remove an element from the List based on the specified index position.
RemoveRange It is used to remove a range of elements from the List.
Reverse It reverse the order of List elements.
Sort It sorts the elements in the List.
ToArray It will copies the elements of List to new array object.

C# Generic List (List<T>) Example

Following is the example of using the generic list (List<T>) in c# programming language.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

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

            lst.Add(1);

            lst.Add(8);

            lst.Add(45);

            List<string> lst2 = new List<string>();

            lst2.Add("Hi");

            lst2.Add("Welcome");

            lst2.Add("to");

            lst2.Add("Tutlane");

            Console.WriteLine("List1 Elements Count: " + lst.Count);

            Console.WriteLine("List1 Capacity: " + lst.Capacity);

            Console.WriteLine("*********List1 Elements********");

            // Accessing list elements

            foreach (var item in lst)

            {

                Console.WriteLine(item);

            }

            Console.WriteLine("List2 Elements Count: " + lst2.Count);

            Console.WriteLine("List2 Capacity: " + lst2.Capacity);

            Console.WriteLine("*********List2 Elements********");

            foreach (var item in lst2)

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we are able to define a new generic lists (lst, lst2) collection by using System.Collections.Generic  namespace. Here, we added only the defined data type (string) values to the newly created lists (lst, lst2) by using Add method and accessing those generic list (lst, lst2) elements by using foreach loop.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Generic List Example Result

 

This is how we can use generic list in c# to store the group of defined type elements based on our requirements.

 

Following are the some of useful examples to work with generic list in c# programming language.

C# Add Elements to List

In c#, we can add an elements to the list either by using Add / AddRange methods or at the time of initialization based on our requirements.

 

Following is the example of adding an elements to the list using Add or AddRange methods in c#.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    public class User

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Location { get; set; }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

            List<int> lst = new List<int>() { 1, 8, 45, 70 };

            Console.WriteLine("List1 Elements Count: " + lst.Count);

            Console.WriteLine("*********List1 Elements********");

            // Accessing list elements

            foreach (var item in lst)

            {

                Console.WriteLine(item);

            }

            //AddRange method

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

            lst2.AddRange(lst);

            Console.WriteLine("List2 Elements Count: " + lst2.Count);

            Console.WriteLine("*********List2 Elements********");

            foreach (var item in lst2)

            {

                Console.WriteLine(item);

            }

            List<User> users = new List<User>(){

            new User{Id= 1, Name= "Suresh Dasari", Location= "Hyderabad"},

            new User{Id = 2, Name = "Rohini Alavala", Location = "Guntur"}

            };

            users.Add(new User { Id = 3, Name = "Trishika Dasari", Location = "Guntur" });

            users.Add(new User { Id = 4, Name = "Praveen Alavala", Location = "Eluru" });

            Console.WriteLine("List3 Elements Count: " + users.Count);

            Console.WriteLine("*********List3 Elements********");

            foreach (User u in users)

            {

                Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", u.Id, u.Name, u.Location);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we created a multiple lists (lst, lst2, users) and adding an elements to the lists in different ways like added some of the elements during initialization time and some other elements by using Add & AddRange methods.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Add Elements to List Example Result

C# Access List Elements

In c#, we have a different ways to access list elements i.e. either by using index positions or by iterating through the list using for / foreach loops.

 

Following is the example of accessing a list elements in different ways.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    public class User

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Location { get; set; }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

            List<int> lst = new List<int>() { 1, 8, 45, 70 };

            Console.WriteLine("*********Access Elements with Index Position********");

            Console.WriteLine("Element at 0: " + lst[0]);

            Console.WriteLine("Element at 2: " + lst[2]);

            // Creating List

            List<User> users = new List<User>(){

            new User{Id= 1, Name= "Suresh Dasari", Location= "Hyderabad"},

            new User{Id = 2, Name = "Rohini Alavala", Location = "Guntur"},

            new User { Id = 3, Name = "Trishika Dasari", Location = "Guntur" },

            new User { Id = 4, Name = "Praveen Alavala", Location = "Eluru" }

            };

            Console.WriteLine("*********Access Elements with For Loop********");

            // for loop to access list elements

            for (int i = 0; i < users.Count; i++)

            {

                Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", users[i].Id, users[i].Name, users[i].Location);

            }

            Console.WriteLine("*********Access Elements with Foreach Loop********");

            // foreach loop to access list elements

            foreach (User u in users)

            {

                Console.WriteLine("Id:{0}, Name:{1}, Location:{2}", u.Id, u.Name, u.Location);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we are accessing generic list elements in different ways by using index positions, for and foreach loops based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Access List Elements Example Result

C# Insert Elements into List

In c#, we can insert an elements into the list either by using Insert() or InsertRange() methods.

 

Following is the example of inserting an elements into the list by using Insert and InsertRange methods in c#.

 

using System;

using System.Collections.Generic;

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

            List<int> lst = new List<int>() { 1, 8, 45, 70 };

            // inserting elements into list

            lst.Insert(0, 10);

            lst.Insert(3, 50);

            List<int> lst2 = new List<int>() { 200, 300 };

            // inserting lst2 into lst at position 2

            lst.InsertRange(2, lst2);

            Console.WriteLine("*********ArrayList Elements********");

            foreach (var item in lst)

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we inserted an elements into list at different index positions (0, 3) by using Insert() method. Same way, by using InsertRange() method we are inserting all the element of newly created list (lst2) into lst at index position 2.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Insert Elements into List Example Result

C# Remove Elements from List

In c#, we have a different methods to remove an elements from the list i.e. either by using Remove() or RemoveAt() or RemoveRange() methods.

 

Following is the example of deleting an elements from the list in c# programming language.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

            List<int> lst = new List<int>() { 10, 20, 30, 40, 50, 60, 70, 80 };

            // Removing an element which is having a value 50

            lst.Remove(50);

            // Removing an element at index 2

            lst.RemoveAt(2);

            // Removing 2 elements starting from index 3

            lst.RemoveRange(3, 2);

            Console.WriteLine("*********List Elements********");

            foreach (var item in lst)

            {

                Console.WriteLine(item);

            }

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a Remove() method to delete particular value of element from list and used a RemoveAt() method to delete an element at specified index position.

 

Same way, we used RemoveRange() method to delete specified number of elements from list starting from the specified index position.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Remove Elements from List Example Result

 

In case, if you want to remove all the elements from list, then use Clear() method.

 

Same way, we can use different methods like Find() method to find an elements of list and Reverse() method to reverse the order of list elements, etc. based on our requirements.

C# List Check If Item Exists

 By using Contains() method, we can check whether the specified element exists in list or not. In case, if it exists it will return true otherwise false.

 

Following is the example of using Contains() method to check for an item exists in list or not in c#.

 

using System;

using System.Collections.Generic;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            // Creating and initializing list

            List<int> lst = new List<int>() { 10, 20, 30, 40, 50, 60, 70, 80 };

            // Check for an item 50 exists in list or not

            Console.WriteLine("Item Exists: " + lst.Contains(50));

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a Contains() method to check for an item (50) exists in list (lst) or not.

 

When we execute above c# program, we will get the result like as shown below.

 

Item Exists: True

C# List (List<T>) Overview

Following are important points which needs to remember about list in c#.

 

  • List is used to store an elements of same data type and the size of list can grow or shrink dynamically by adding or removing an elements.
  • List is a generic type of collection and available with System.Collections.Generic namespace.
  • We can access the list elements either by using loops (for and foreach) or with particular index position.
  • List<T> can be assigned to IList<T> or List<T> type of variable and we can store multiple null and duplicate values in list based on our requirement.
  • List provided a different methods to perform a multiple operations like add, insert, delete, sort, reverse, etc. on elements of arraylist.