List Implementation in C#
In C# programming, a generic collection is known to as a "list" and is used to store elements or objects in the form of a System. Collection.Common namespace. A list and an array list will do the same tasks. However, a list is a generic collection, an array list is not a generic collection. The List's size varies based on demand because it is dynamic.
Important Points:
- The ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, and IReadOnlyList<T> interfaces are all implemented by the List class together with the ICollection, IEnumerable, and IList interfaces.
- It supports null as a valid value for reference types and allows for the duplication of items.
- The List's Capacity is automatically expanded by reallocating the internal array if the Count reaches the Capacity.
- The List's elements are not automatically sorted. Instead, they are retrieved using zero-based indexes.
Let's create a list:
Step 1:
System.Collection.Generic namespace is included. And also it will utilize the generics namespace in your program by using a keyword.
Step 2:
Using the List <T> class create a list.
Step 3:
List<T> class offers two alternative methods for adding elements to your List and the techniques.
NOTE: Additionally, you can add by using collection initializers. As shown in the below example:
Example:
// Creating List using List class
// and Adding elements using the
//Collection initializers
List<string> my_list1 = new List<string>() { “Java”, “Java123”, “Javatpoint” };
Step 4:
Use one of the following approaches to access the List elements:
- Using the for-each loop: Use the foreach loop to access the items and elements of the List.
- Using ForEach()method: The specified action is carried out on each element of the <ListT> using this method.
- Using Indexers: Indexers can access the List's objects and items.
Example:
Program:
The following program is as follows:
// C# program to illustrate how
// to create a list
using System;
using System.Collections.Generic;
class Preethi {
// Main Method
static public void Main()
{
// Creating a list using the List class
// and List<T>() Constructor
List<int> my_list = new List<int>();
// Adding elements to List
// Using Add() method
my_list.Add(1);
my_list.Add(10);
my_list.Add(100);
my_list.Add(1000);
my_list.Add(10000);
my_list.Add(100000);
my_list.Add(1000000);
// Accessing elements of my_list
// Using foreach loop
foreach(int a in my_list)
{
Console.WriteLine(a);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp1.png)
Example:
Program:
The following program is as follows:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a list of integers
List<int> numbers = new List<int>();
// Adding elements to the List
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
// Accessing elements by index
int firstNumber = numbers[0]; // 10
int secondNumber = numbers[1]; // 20
// Modifying an element
numbers[2] = 40;
// Removing an element
numbers.Remove(20);
// Iterating over the List
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp2.png)
In previously mentioned example, we build a List<int> called numbers and add three integers. We can access and alter elements according to their index by using the square bracket notation ([]). We can also delete components based on their value using the delete method. The List and Output of each element are then examined using a for each loop.
To make a list of objects of that type, swap out int with any other valid C# type.
Example:
Program:
The following program is as follows:
// C# program to illustrate how
// to remove objects from the List
using System;
using System.Collections.Generic;
class Preethi {
// Main Method
static public void Main()
{
// Creating a list using the List class
// and List<T>() Constructor
List<int> my_list = new List<int>();
// Adding elements to List
// Using Add() method
my_list.Add(1);
my_list.Add(10);
my_list.Add(100);
my_list.Add(1000);
my_list.Add(10000);
my_list.Add(100000);
my_list.Add(1000000);
my_list.Add(10000000);
my_list.Add(100000000);
// Initial Count
Console.WriteLine("Initial count:{0}", my_list.Count);
// After using Remove() method
my_list.Remove(10);
Console.WriteLine("2nd count:{0}", my_list.Count);
// After using RemoveAt() method
my_list.RemoveAt(4);
Console.WriteLine("3rd count:{0}", my_list.Count);
// After using RemoveRange() method
my_list.RemoveRange(0, 2);
Console.WriteLine("4th count:{0}", my_list.Count);
// After using Clear() method
my_list.Clear();
Console.WriteLine("5th count:{0}", my_list.Count);
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp3.png)
How to sort a list?
This method compares list elements using a given IComparer<T> implementation or a specific or default IComparer<T> implementation. It sorts all or some of the elements in the List<T>.
Example:
Program:
The following program is as follows:
// C# program to illustrate how
//Sort a list
using System;
using System.Collections.Generic;
class Preethi {
// Main Method
static public void Main()
{
// Creating a list using the List class
// and List<T>() Constructor
List<int> my_list = new List<int>();
// Adding elements to List
// Using Add() method
my_list.Add(496);
my_list.Add(1000);
my_list.Add(100);
my_list.Add(10);
my_list.Add(10000);
my_list.Add(10000000);
my_list.Add(1000000);
my_list.Add(100000);
my_list.Add(0000);
// Without Sorted List
Console.WriteLine("UnSorted List:");
foreach(int a in my_list)
{
Console.WriteLine(a);
}
// After Sort method
my_list.Sort();
Console.WriteLine("Sorted List:");
foreach(int a in my_list)
{
Console.WriteLine(a);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp4.png)
How to create a List?
Using the List <T> constructor accepts an int-type argument representing the List's Capacity; we can create a list. If we don't provide the Capacity, the list size will be dynamic every time a new element is added.
The list size will automatically increase if the capacity value is used when creating the List and more entries are added than the defined Capacity allows.
How to remove elements from the List?
The following methods will be provided by the List <T> class and it can be used to remove list elements:
- Remove(T): This method removes an object's initial occurrence from a list.
- RemoveAll(Predicate<T>): This method removes all the elements that satisfy, and its predicate's requirements are eliminated.
- Clear(): The List<T> can have all of its elements removed by using the Clear() method.
Adding elements to the List:
After creating a list, we can add things later. And methods are:
1. Create List:
List<int> lst = new List<int>
{
1,2,3,4,5,6
};
2. Add items after creating a list:
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(2);
lst.Add(3);
lst.Add(4);
lst.Add(5);
lst.Add(3);
Properties of a list:
Two properties included in the List are:
1. Capacity
2. Count
Read all elements of a list:
We must loop around a list to get all its components. We have to use for or for each loop to obtain the elements. The code for collecting all the items utilizing both loops and printing the values of the elements is shown below:
1. Using a foreach loop:
foreach (var item in lst)
{
Console.WriteLine(item);
}
2. Using for loop:
The loop in this method must continue until the last element in the List. To do it, I used the List's Count property.
for (int i = 0; i < lst.Count; i++)
{
Console.WriteLine(lst[i]);
}
From both the methods, the result will be the same. I'm using the example from the previous List. And the result is:
OUTPUT:
1
2
3
4
5
3
Remove elements from a list:
We can use several list methods to remove items from a list.
1. Remove(T item): The first instance of an element in a list is removed by using this procedure.
lst.Remove(3); // Removes the first occurrence of element 3
2. RemoveAll(Predicate<T> match): This method removes all elements from a list that match the condition by defining the predicate. The predicate is a required parameter.
lst.RemoveAll(x=>x==3); // Removes all the elements 3
3. RemoveAt(int index): This procedure removes The element from the specified index. The index must be provided as a parameter.
lst.RemoveAt(0); // Removes 0th index element from a list
4. RemoveRange(int index, int count): This procedure removes the element from the specified Count to the given index. The initial index and Count must be supplied as parameters.
lst.RemoveRange(0,2); // Removes element 1,2 because the starting index is 0 and Count is 2
5. Clear(): All list elements are removed with this method.
Methods of List in C# with examples:
The following list class methods are as follows:
1. Add(T): The List's end can have an object added using this technique. A reference type may have a null value added to it.
Example:
Program:
The following program will be:
using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<int> lstNum = new List<int>(){1, 2, 3, 4};
//Adding 5 at the end of the List
sternum.Add(5);
foreach(int num in lstNum)
{
Console.WriteLine(num);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp5.png)
2. Clear(): To eliminate every element from the List, apply this method.
3. Insert( Int32, T ): A specific location may be added to the list using this method.
Example:
Program:
The following program will be:
using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<string> lstCities = new List <string>(){"Mumbai", "Pune", "Bengaluru"};
//inserting element at third position
lstCities.Insert(2, "Chennai");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp6.png)
4. RemoveAt( Int32 ): Using this method, a list item at the specified position is removed.
5. Sort(): The List's elements are sorted using this method's default comparer.
Example:
Program:
The following program will be:
using System;
using System.Collections.Generic;
public class ListDemo
{
public static void Main()
{
List<string> lstCities = new List <string>(){"Mumbai","Pune","Bengaluru"};
Console.WriteLine("Initial list values");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
//sorting elements in ascending order
lstCities.Sort();
Console.WriteLine("\nList after sorting in ascending order");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
//sorting elements in descending order by calling Reverse()
lstCities.Reverse();
Console.WriteLine("\nList after sorting in descending order");
foreach(string city in lstCities)
{
Console.WriteLine(city);
}
}
}
OUTPUT:
The Output for the following program will be:
![List Implementation in C#](https://static.tutorialandexample.com/csharp/list-implementation-in-csharp7.png)
The List was sorted using Sort() in the program as mentioned above's first step to ascending order. The Reverse() function was then used on the sorted List to sort it in descending order. We must implement an IComparable interface or use LINQ to sort a list of custom objects. We may sort a list of int, string, and other types using the Sort() method. As shown in the example below, we can arrange this kind of List in another method:
Conclusion:
A list is a dynamic data structure in C# that enables elements in addition, removal, and index access.
- The built-in List class in C# is the most popular list creation method. It offers a general list that can hold components of any type. Along with other practical techniques like sorting and searching, it supports adding, deleting, and accessing elements by index.
- Using an array - Due to the array's predetermined size at development, this method is less flexible than List<T>. The array must be enlarged in order to add or remove elements, which can be unpleasant.
- Making a unique list class: Making a unique class that implements a list is another choice. While requiring more programming work, this approach provides greater customization and flexibility.
Overall, the implementation option will be determined by the program's unique requirements, such as the expected length of the List, the frequency of adding and removing components.