Generic List in C#

Generic List in C# with Examples

In this article, I am going to discuss the Generic List in C# with examples. Please read our previous article before proceeding to this article where we discussed the Generics in C#. The generic List<T> class is present in System.Collections.Generic namespace. The List<T> Collection class is one of the most widely used generic collection class in real-time applications.

The List<T> generic collection class represents a strongly typed list of objects which can be accessed by using the index. It also provides methods which can be used for search, sort and manipulate the list items.

We can create a collection of any type by using the generic list class in C#. For example, if we want then we can create a list of string, list of integers and even though it is also possible to create a list of the user-defined complex type such as a list of customers, list of products, etc. The important point that we need to keep in mind is the size of the collection grows automatically when we add items into the collection.

Methods and Properties of Generic List Collection class in C#:

Following are some of the useful methods and properties of the List collection class in C#.

Add(T value): This method is used to Add an item to the end of the list collection.
Remove(T value): This method is used to remove the first occurrence of a specific item from the collection.
RemoveAt(int index): This methods takes the index position of the elements and then remove that element from the collection.
Insert(int index, T value): This method is used to inserts an element into the collection at a specified index position.
Capacity: This property is used to return the capacity of the collection means how many elements you can insert into the collection.

Example of Generic List in C#:

Let us see an example to understand the above methods and properties of Generic List in C#. The following example is self-explained. So please go through the comments.

using System;
using System.Collections.Generic;
namespace GenericListCollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Createing an interger list
            //it is going to store only integer value
            List<int> integerList = new List<int>();

            Console.WriteLine("Initial Capacity: " + integerList.Capacity);
            integerList.Add(10);
            Console.WriteLine("Capacity after adding first item: " + integerList.Capacity);
            integerList.Add(20);
            integerList.Add(30);
            integerList.Add(40);
            Console.WriteLine("Capacity after adding fourth item: " + integerList.Capacity);
            integerList.Add(60);
            Console.WriteLine("Capacity after adding 5th element: " + integerList.Capacity);

            //Printing the List items using for loop 
            Console.WriteLine("Printing the List items using for loop:");
            for (int i = 0; i < integerList.Count; i++)
            {
                Console.Write(integerList[i] + "  ");
            }
            Console.WriteLine();

            //Removing the values from the middle of the list
            //here we are removing by value
            integerList.Remove(30);

            //You can also remove element by using index position
            //integerList.RemoveAt(2);

            //Printing the list items using foreach loop after
            //removing an element from the collection
            Console.WriteLine("List items after removing the value 30 :");
            foreach (int item in integerList)
            {
                Console.Write(item + "  ");
            }
            Console.WriteLine();

            //inserting values into the middle of the list collection
            integerList.Insert(2, 25);

            // Printing the values of the collection using foreach loop after
            // inserting an element into the middle of the collection
            Console.WriteLine("List items after inserting the value 25 in the index 2");
            foreach (int item in integerList)
            {
                Console.Write(item + "  ");
            }
            Console.WriteLine();

            // creating new ArrayList collection by passing the old 
            // array list as parameter
            List<int> newIntegerList = new List<int>(integerList);

            Console.WriteLine("Initial capacity of new list collection:" + newIntegerList.Capacity);

            // Printing the values of the new list collection using foreach loop
            Console.WriteLine("Printing the new List items which is created from the old list");
            foreach (int item in newIntegerList)
            {
                Console.Write(item + "  ");
            }
            Console.ReadKey();
        }
    }
}

Output:

Generic List in C#

Let us see an example of the List Collection class with a complex type.
using System;
using System.Collections.Generic;

namespace ListCollectionDemo
{
    public class Program
    {
        public static void Main()
        {
            // Create Employee Objects
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 5000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 7000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 5500
            };
            Employee emp4 = new Employee()
            {
                ID = 104,
                Name = "Sambit",
                Gender = "Male",
                Salary = 6500
            };
            
            // Create a List of Employees
            List<Employee> listEmployees = new List<Employee>();
            
            listEmployees.Add(emp1);
            listEmployees.Add(emp2);
            listEmployees.Add(emp3);

            // We can retrieve the Items from a list collection by using index. 
            // The following line of code will retrieve the employee from the list. 
            // The List index is also 0 based.
            Employee emp = listEmployees[0];

            Console.WriteLine("Retrive the First employee by index");
            Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                     emp.ID, emp.Name, emp.Gender, emp.Salary);
            Console.WriteLine();
            
            // retrieving the list using for loop
            Console.WriteLine("Retriving the list using for loop");
            for (int i = 0; i < listEmployees.Count; i++)
            {
                Employee employee = listEmployees[i];
                Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                         employee.ID, employee.Name, employee.Gender, employee.Salary);
            }
            Console.WriteLine();

            // retrieving the list using foreach loop
            Console.WriteLine("Retriving the list using foreach loop");
            foreach (Employee e in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                        e.ID, e.Name, e.Gender, e.Salary);
            }
            Console.WriteLine();
            
            // inserting an employee into the index position 1.
            listEmployees.Insert(1, emp4);

            // retrieving the list after inserting the employee in index position 1
            Console.WriteLine("Retriving the list after inserting new employee in index 1");
            foreach (Employee e in listEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                        e.ID, e.Name, e.Gender, e.Salary);
            }
            Console.WriteLine();

            //If you want to get the index postion of a specific employee
            //then use Indexof() method as shown below
            Console.WriteLine("Index of emp3 object in the List = " +
                    listEmployees.IndexOf(emp3));
            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}
OUTPUT:

Generic List in C# with complex type example

Note: All the generic classes in C# are strongly typed. That means if we have created a List of type Employees, then we can only add objects of type Employees into the list. If we try to add an object of different type, then we will get a compile-time error. 

Let us discuss some of the useful methods of generic list collection class in C#:

The Generic List in C# provides a lot of useful methods which we can use to perform some operations on a collection of List Type. The List Collection class provides the following functions.

Contains() Method:
The Contains() method is used to determine whether the specified item exists or not in the list. If the specified item exists then it will return true else return false.

Exists() Method:
The Exists() method is also used to check or determine whether an item exists or not in a list based on a condition. If the item exists then it will return true else it will return false.

Find() Method:
The Find() method is used to find the first element from a list based on a condition which is specified by a lambda expression.

FindLast() Method:
The FindLast() method is used to searches for an element that matches the conditions specified by predicate. If it found any elements with that specified condition then it returns the Last matching element from the list.

FindAll() Method:
The FindAll() method is used to retrieves all the elements from a list that matches the conditions specified by a predicate. 

FindIndex() Method:

The FindIndex() method is used to return the index position of the first element that matches the conditions specified by a predicate. The point that you need to remember is the index here in generic collections are zero-based. This method returns -1 if an element that matches the specified conditions is not found. There are 2 other overloaded versions of this method is available, one of the overload version allows us to specify the range of elements to search within the list.

FindLastIndex() Method:

The FindLastIndex() Method searches for an element in the list that matches the condition specified by the lambda expression and then returns the index of the last occurrence of the item within the list. There are 2 other overloaded version of this method is available, one of the overload version allows us to specify the range of elements to search within the list.

Let us understand all the above method of List Collection class with an example.
using System;
using System.Collections.Generic;

namespace ListCollectionDemo
{
    public class Program
    {
        public static void Main()
        {
            // Create Employee Objects
            Employee emp1 = new Employee()
            {
                ID = 101,
                Name = "Pranaya",
                Gender = "Male",
                Salary = 5000
            };
            Employee emp2 = new Employee()
            {
                ID = 102,
                Name = "Priyanka",
                Gender = "Female",
                Salary = 7000
            };
            Employee emp3 = new Employee()
            {
                ID = 103,
                Name = "Anurag",
                Gender = "Male",
                Salary = 5500
            };
            Employee emp4 = new Employee()
            {
                ID = 104,
                Name = "Sambit",
                Gender = "Male",
                Salary = 6500
            };

            //Creating a list of type Employee
            List<Employee> listEmployees = new List<Employee>();
            listEmployees.Add(emp1);
            listEmployees.Add(emp2);
            listEmployees.Add(emp3);
            listEmployees.Add(emp4);

            // use Contains method to check if an item exists or not in the list 
            if (listEmployees.Contains(emp2))
            {
                Console.WriteLine("Employee2 object exists in the list");
            }
            else
            {
                Console.WriteLine("Employee2 object does not exist in the list");
            }
            Console.WriteLine("");

            // Use Exists method when you want to check if an item exists or not
            // in the list based on a condition
            if (listEmployees.Exists(x => x.Name.StartsWith("P")))
            {
                Console.WriteLine("List contains Employees whose name starts with P");
            }
            else
            {
                Console.WriteLine("List does not contain any employee whose name starts with P");
            }
            Console.WriteLine("");

            // Use Find() method, if you want to searche an element by a conditions 
            Employee emp = listEmployees.Find(employee => employee.Gender == "Male");
            Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                                emp.ID, emp.Name, emp.Gender, emp.Salary);
            Console.WriteLine("");

            // Use FindLast() method when you want to searche an item by a conditions
            // and returns the Last matching item from the list
            Employee lastMatchEmp = listEmployees.FindLast(employee => employee.Gender == "Male");
            Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                            lastMatchEmp.ID, lastMatchEmp.Name, lastMatchEmp.Gender, lastMatchEmp.Salary);
            Console.WriteLine("");

            // Use FindAll() method when you want to return all the items that
            // matches the conditions
            List<Employee> filteredEmployees = listEmployees.FindAll(employee => employee.Gender == "Male");
            foreach (Employee femp in filteredEmployees)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Gender = {2}, Salary = {3}",
                                femp.ID, femp.Name, femp.Gender, femp.Salary);
            }
            Console.WriteLine("");

            // Use FindIndex() method when you want to return the index of the first item
            // by a condition
            Console.WriteLine("Index of the first matching employee object whose Gender is Male = " +
                listEmployees.FindIndex(employee => employee.Gender == "Male"));
            Console.WriteLine("");

            // Use FindLastIndex() method when you want to return the index of the last item 
            // by a condition
            Console.WriteLine("Index of the Last matching employee object whose Gender is Male = " +
                listEmployees.FindLastIndex(employee => employee.Gender == "Male"));

            Console.ReadKey();
        }
    }
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}

OUTPUT:

Methods of Generic List in C#

In the next article, I am going to discuss the Range Methods of List class in C# with examples.

SUMMARY:

In this article, I try to explain the Generic List in C# with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *