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.

Output:

Generic List in C#

Let us see an example of the List Collection class with a complex type.
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 *