The List<T> category in C# programming is a popular choice among various collection types, providing resizable arrays to streamline data handling and modification. When dealing with lists, a common activity involves retrieving and modifying elements at specific indexes.
In this article, we will explore the concepts of accessing and modifying elements at specified positions within a C# List.
Getting an Element at a Specified Index:
A C# List's indexer enables retrieval of an element at a specific index within the list. By utilizing the indexer, one can retrieve elements from the list by enclosing the index within square brackets. The following is the syntax for accessing an element at a designated index:
// Syntax:
T element = myList[index];
In this code structure, myList symbolizes an object of the List <T> class, with the index indicating the specific position from which the element will be fetched.
Example:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a List of integers
List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };
// Getting the element at index 2
int elementAtIndex2 = numbers[2];
// Displaying the result
Console.WriteLine($"Element at index 2: {elementAtIndex2}");
}
}
Output:
Element at index 2: 30
In this instance, a List named "numbers" is generated with predefined values. By utilizing the list's indexer, the value at index 2 (which is 30 in this scenario) is obtained and assigned to the variable "elementAtIndex2." Subsequently, the code outputs the outcome, exhibiting "Element at index 2: 30." This illustration effectively demonstrates the straightforward and efficient process of accessing a particular element within a List, underscoring the convenience and speed of employing the List<T> class in C# for handling arrays.
Setting an Element at a Specified Index:
In the C# language, when we need to assign a value to an element at a specific index in a List, we follow the same approach by using the indexer along with an assignment statement. The format for assigning a value to an element at a particular index is as demonstrated below:
// Syntax:
myList[index] = newValue;
In this scenario, the myList object represents an example of the List<T> class. Here, we aim to update the value at a specific index with a new value, denoted by the variable #newValue#.
Example:
using System;
using System.Collections.Generic;
class Program
{
static void Main ()
{
// Creating a List of strings
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry", "Date", "Fig" };
// Displaying the original list
Console.WriteLine("Original list:");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
// Setting a new value at index 2
fruits[2] = "Grapes";
// Displaying the modified list
Console.WriteLine("\nModified list:");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
Output:
Original list:
Apple
Banana
Cherry
Date
Fig
Modified list:
Apple
Banana
Grapes
Date
Fig
Explanation:
This illustration showcases a List called fruits containing predefined strings. The initial list is demonstrated through a foreach loop. Subsequently, the list's indexer is utilized to update index 2 with a new value ("Grapes"). The adjusted list is then displayed. The code exemplifies fundamental list manipulation, illustrating the process of altering items dynamically. The result exhibits both the original and updated lists, emphasizing the change made to the second item from "Cherry" to "Grapes." This concise code snippet serves as a demonstration of updating elements within a List in C#.
Conclusion:
In summary, the C# code examples showcased earlier demonstrate that the List<T> class combines the advantages of a dynamic array with user-friendly functionalities. Whether working with elements at particular indexes, Lists offer a straightforward and efficient solution. The indexer significantly enhances code readability by facilitating easy item retrieval. The initial example illustrates the process of accessing an element at a specified index in the List, emphasizing the importance of direct access in Lists.
In the second scenario of the program, Lists demonstrate their ability to assign new values dynamically at a particular index location, showcasing the List <T> class's effectiveness in updating data dynamically. These instances underscore the importance of utilizing Lists for handling data collections, a crucial aspect of C# operations. Lists play a vital role in C# programming, empowering developers to efficiently handle data and facilitate the creation of top-notch applications. Together, these illustrations offer valuable insights into the seamless integration of Lists into the C# programming language, especially in comparison to the effective implementation of arrays.