C# List (List<T>)

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

 

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

C# List Declaration

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

 

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

 

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

If you observe the above list declaration, we created a generic list (lst) with an instance of list class using type parameter (T) as a 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 the type of elements to be accepted by the list.

 

In c#, the generic list (List<T>) is an implementation of the IList<T> interface, so we can also use IList<T> interface to create an object of the 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 the above example, we defined a list (lst) with string data type to store only string elements.

C# List Properties

The following are some of the commonly used properties of the generic list in the 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 the list.
Item It is used to get or set an element at the specified index.

C# List Methods

The following are some of the commonly used methods of the generic list to perform add, search, insert, delete or sort operations in the 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 the specified collection at the end of the List.
Clear It will remove all the elements from the List.
Contains It is used to determine whether the specified element exists in the List or not.
CopyTo It is used to copy the entire List to a compatible one-dimensional array.
Find It is used to search for an element that matches the conditions defined by the specified predicate and returns the first occurrence of the List.
FindAll It is used to retrieve all the elements that match the conditions defined by the specified predicate.
ForEach It is used to iterate through the List to access 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 the specified collection into a List starting from the specified index.
Remove It is used to remove the first occurrence of a 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 reverses the order of List elements.
Sort It sorts the elements in the List.
ToArray It will copy the elements of the List to new array objects.

C# Generic List (List<T>) Example

Following is the example of using the generic list (List<T>) in the 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 the 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 lists (lst, lst2) elements by using the foreach loop.

 

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

 

C# Generic List Example Result

 

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

 

The following are some useful examples to work with a generic list in the c# programming language.

C# Add Elements to List

In c#, you can add 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 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 the above example, we created multiple lists (lst, lst2, users) and adding elements to the lists in different ways, like adding some of the elements during initialization time and some other elements by using Add & AddRange methods.

 

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

 

C# Add Elements to List Example Result

C# Access List Elements

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

 

Following is the example of accessing 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 the above example, we are accessing generic list elements in different ways by using index positions for and foreach loops based on our requirements.

 

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

 

C# Access List Elements Example Result

C# Insert Elements into List

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

 

Following is the example of inserting 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 the above example, we inserted elements into the list at different index positions (0, 3) by using the Insert() method. Similarly, using the InsertRange() method, we are inserting all the elements of a newly created list (lst2) into lst at index position 2.

 

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

 

C# Insert Elements into List Example Result

C# Remove Elements from List

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

 

Following is the example of deleting the elements from the list in the 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 the above example, we used a Remove() method to delete the particular value of an element from the list. We used a RemoveAt() method to delete an element at the specified index position.

 

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

 

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

 

C# Remove Elements from List Example Result

 

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

 

Same way, you can use different methods like Find() method to find elements of the list and the 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 the list or not. In case if it exists, it will return true otherwise false.

 

Following is the example of using the Contains() method to check for an item that exists in the 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 the above example, we used a Contains() method to check for an item (50) exists in the list (lst) or not.

 

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

 

Item Exists: True

C# List (List<T>) Overview

The following are the important points that need to remember about a list in c#.

 

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