![]() |
VOOZH | about |
In C#, a List is a generic collection used to store the elements or objects in the form of a list defined under System.Collections.Generic namespace. It provides the same functionality as ArrayList, the difference is a list is generic whereas ArrayList is a non-generic collection. It is dynamic means the size of the list grows, according to the need.
Example:
C# Java Javascript
The list class has 3 constructors which are used to create a list as follows:
Example:
Default Constructor: 10 20 Constructor with IEnumerable: 10 20 Constructor with Initial Capacity: 10 20
Step 1: Including System.Collections.Generics namespace.
using System.Collections.Generic;
Step 2: Create a list using the List<T> class.
List<T> list_name = new List<T>();
For adding elements list, The List<T> class provides two different methods which are:
// Add element using Add method
list.Add(1);
list.Add(2);// Adding elements using the
// Collection initializers
List<string> my_list1 = new List<string>() { “geeks”, “Geek123”, “GeeksforGeeks” };
We can access the elements of the list by using the following ways:
foreach loop: We can use a foreach loop to access the elements/objects of the List.
// Accessing elements of my_list
// Using foreach loop
foreach(int a in my_list)
{
Console.WriteLine(a);
}
ForEach loop: It is used to perform the specified action on each element of the List<T>.
// Accessing elements of my_list
// Using ForEach method
my_list.ForEach(a = > Console.WriteLine(a));
for loop: We can use a for loop to access the elements/objects of the List.
// Accessing elements of my_list
// Using for loop
for (int a = 0; a < my_list.Count; a++)
{
Console.WriteLine(my_list[a]);
}
Indexers: Indexers used to access the elements/objects of the List.
// Accessing elements of my_list
// Using indexers
Console.WriteLine(my_list[3]);
Console.WriteLine(my_list[4]);
Example:
Accessing elements using foreach loop: 10 20 30 Accessing elements using ForEach method: 10 20 30 Accessing elements using for loop: 10 20 30 Accessing elements using indexers: Element at index 2: 30
Example:
Initial count:5 after removing 3 2nd count:4 after removing at 3th index 3rd count:3 after removing range from 0 to 2 4th count:1 after removing all elements 5th count:0
We can sort the elements by using the Sort() method. Used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
Example:
UnSorted List: 2, 1, 5, 3, 50, Sorted List: 1, 2, 3, 5, 50,