In C#, a List is a generic collection used to store the elements or objects in the form of a list defined under System.Collection.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.
- The List class implements the ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IEnumerable, and IList interface.
- It can accept null as a valid value for reference types and also allows duplicate elements.
- If the Count becomes equal to Capacity, then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
- The elements present in the list are not sorted by default and elements are accessed by zero-based index.
Example:
C#
// Creating and printing a List
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
List<string> l = new List<string> { "C#", "Java", "Javascript" };
foreach (string name in l)
{
Console.WriteLine(name);
}
}
}
OutputC#
Java
Javasccript
Creating List Using Constructors
The list class has 3 constructors which are used to create a list as follows:
- List<T>(): This constructor is used to create an instance of the List<T> class that is empty and has the default initial capacity.
- List<T>(IEnumerable): This constructor is used to create an instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.
- List<T>(Int32): This constructor is used to create an instance of the List<T> class that is empty and has the specified initial capacity.
Example:
C#
// Creating List using Constructors
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// default constructor creates an empty list
List<int> list = new List<int>();
list.Add(10);
list.Add(20);
Console.WriteLine("Default Constructor: ");
foreach (var item in list)
{
Console.WriteLine(item);
}
// Construnctors from IEnumerable
int[] num = { 10, 20 };
List<int> enumerableList = new List<int>(num);
Console.WriteLine("Constructor with IEnumerable: ");
foreach (var item in enumerableList)
{
Console.WriteLine(item);
}
// Constructor with Initial Capacity
List<int> Clist = new List<int>(2);
Clist.Add(10);
Clist.Add(20);
Console.WriteLine("Constructor with Initial Capacity: ");
foreach (var item in Clist)
{
Console.WriteLine(item);
}
}
}
OutputDefault Constructor:
10
20
Constructor with IEnumerable:
10
20
Constructor with Initial Capacity:
10
20
Steps to Create a List
Step 1: Including System.Collection.Generics namespace.
using System.Collections.Generic;
Step 2: Create a list using the List<T> class.
List list_name = new List();
Performing Different Operations on List
1. Adding Elements
For adding elements list, The List<T> class provides two different methods which are:
- Add(T): This method is used to add an object to the end of the List<T>.
- AddRange(IEnumerable<T>): This method is used to add the elements of the specified collection to the end of the List<T>.
// 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” };
2. Accessing List
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));
3. 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:
C#
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a list of integers
List<int> my_list = new List<int> { 10, 20, 30,};
// Accessing elements using foreach loop
Console.WriteLine("Accessing elements using foreach loop:");
foreach (int a in my_list)
{
Console.WriteLine(a);
}
// Accessing elements using ForEach method
Console.WriteLine("Accessing elements using ForEach method:");
my_list.ForEach(a => Console.WriteLine(a));
// Accessing elements using for loop
Console.WriteLine("Accessing elements using for loop:");
for (int i = 0; i < my_list.Count; i++)
Console.WriteLine(my_list[i]);
// Accessing elements using indexers
Console.WriteLine("Accessing elements using indexers:");
Console.WriteLine($"Element at index 2: {my_list[2]}");
}
}
OutputAccessing 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
3. Remove Elements from the List
- Remove(T): This method is used to remove the first occurrence of a specific object from the List.
- RemoveAll(Predicate<T>): This method is used to remove all the elements that match the conditions defined by the specified predicate.
- RemoveAt(Int32): This method is used to remove the element at the specified index of the List.
- RemoveRange(Int32, Int32): This method is used to remove a range of elements from the List<T>.
- Clear(): This method is used to remove all elements from the List<T>.
Example:
C#
// C# program to remove elements from the list
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating list using List class
// and List<T>() Constructor
List<int> l = new List<int>();
// Adding elements to List
// Using Add() method
l.Add(1);
l.Add(2);
l.Add(3);
l.Add(4);
l.Add(5);
// Initial count
Console.WriteLine("Initial count:{0}", l.Count);
l.Remove(3);
Console.WriteLine("after removing 3");
Console.WriteLine("2nd count:{0}", l.Count);
l.RemoveAt(3);
Console.WriteLine("after removing at 4th index");
Console.WriteLine("3rd count:{0}", l.Count);
l.RemoveRange(0, 2);
Console.WriteLine("after removing range from 0 to 2");
Console.WriteLine("4th count:{0}", l.Count);
l.Clear();
Console.WriteLine("after removing all elements");
Console.WriteLine("5th count:{0}", l.Count);
}
}
OutputInitial count:5
after removing 3
2nd count:4
after removing at 4th index
3rd count:3
after removing range from 0 to 2
4th count:1
after removing all elements
5th count:0
4. Sorting a List
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:
C#
// C# program to illustrate how
// sort a list
using System;
using System.Collections.Generic;
class Geeks {
static public void Main()
{
// Creating list using List class
// and List<T>() Constructor
List<int> l = new List<int>();
// Adding elements to List
// Using Add() method
l.Add(2);
l.Add(1);
l.Add(5);
l.Add(3);
l.Add(50);
// Without sorted List
Console.WriteLine("UnSorted List:");
foreach(int a in l) Console.Write(a + ", ");
Console.WriteLine();
// using sort method
l.Sort();
Console.WriteLine("Sorted List:");
foreach(int a in l) Console.Write(a + ", ");
}
}
OutputUnSorted List:
2, 1, 5, 3, 50,
Sorted List:
1, 2, 3, 5, 50,
Ways to Implement List
- Built-In Class List<T>: This is the most common way to implement a list in C#. It provides a generic list that can store elements of any type. It supports adding, removing, and accessing elements by index, as well as other useful methods like sorting and searching.
- LinkedList<T> Class: This class implements a doubly linked list, which is a list in which each element has a reference to both the next and previous elements. It provides efficient insertion and removal of elements in the middle of the list, but accessing elements by index is slower than with List<T>.
- Array: An array can also be used to implement a list in C#. However, this approach is less flexible than using List<T>, as the size of the array is fixed when it is created. To add or remove elements, the array must be resized, which can be inefficient.
- Custom List Class: It is also possible to create a custom class that implements a list. This approach allows for greater flexibility and customization.
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers