Introduction
The List<T>
class in C# is a generic collection that provides a dynamic array, meaning it can grow as needed to accommodate new elements. Lists are part of the System.Collections.Generic
namespace and are widely used due to their flexibility and performance.
Key Features of List
- Dynamic Size: Automatically resizes as elements are added or removed.
- Indexed Access: Provides fast, indexed access to elements.
- Type Safety: Enforces type safety, ensuring that all elements are of the specified type
T
. - Rich API: Includes methods for searching, sorting, and manipulating elements.
Creating a List
Declaration and Initialization
You can declare and initialize a list in several ways:
Example
using System;
using System.Collections.Generic;
namespace ListExample
{
class Program
{
static void Main(string[] args)
{
// Creating an empty list
List<int> numbers = new List<int>();
// Creating a list with initial elements
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
// Adding elements to the list
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// Adding elements at a specific index
fruits.Insert(1, "Blueberry");
// Displaying elements
Console.WriteLine("Numbers: " + string.Join(", ", numbers));
Console.WriteLine("Fruits: " + string.Join(", ", fruits));
}
}
}
Output
Numbers: 1, 2, 3
Fruits: Apple, Blueberry, Banana, Cherry
Common Operations on List
Adding Elements
- Add: Adds an element to the end of the list.
numbers.Add(4);
- AddRange: Adds a collection of elements to the end of the list.
numbers.AddRange(new int[] { 5, 6, 7 });
Inserting Elements
- Insert: Inserts an element at the specified index.
fruits.Insert(1, "Blueberry");
- InsertRange: Inserts a collection of elements at the specified index.
numbers.InsertRange(2, new int[] { 8, 9 });
Removing Elements
- Remove: Removes the first occurrence of the specified element.
numbers.Remove(2);
- RemoveAt: Removes the element at the specified index.
fruits.RemoveAt(1);
- RemoveAll: Removes all elements that match the conditions defined by the specified predicate.
numbers.RemoveAll(n => n > 5);
- Clear: Removes all elements from the list.
fruits.Clear();
Accessing Elements
- Indexer: Accesses elements by their index.
int firstNumber = numbers[0];
string firstFruit = fruits[0];
- Contains: Checks if the list contains the specified element.
bool hasApple = fruits.Contains("Apple");
- IndexOf: Finds the index of the first occurrence of the specified element.
int index = fruits.IndexOf("Banana");
Iterating Through a List
You can iterate through a list using a foreach
loop or a for
loop.
Example
foreach (int number in numbers)
{
Console.WriteLine(number);
}
for (int i = 0; i < fruits.Count; i++)
{
Console.WriteLine(fruits[i]);
}
Sorting and Searching
- Sort: Sorts the elements in the entire list.
numbers.Sort();
- BinarySearch: Searches the sorted list for an element using the binary search algorithm.
int index = numbers.BinarySearch(3);
Practical Example
Let’s create a practical example where we use a List<T>
to manage a collection of students in a class.
Example
using System;
using System.Collections.Generic;
namespace StudentListExample
{
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public Student(int id, string name)
{
Id = id;
Name = name;
}
public override string ToString()
{
return $"ID: {Id}, Name: {Name}";
}
}
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student(1, "John Doe"),
new Student(2, "Jane Smith"),
new Student(3, "Sam Brown")
};
// Adding a new student
students.Add(new Student(4, "Alice Johnson"));
// Removing a student by name
students.RemoveAll(s => s.Name == "Jane Smith");
// Displaying all students
Console.WriteLine("Students:");
foreach (Student student in students)
{
Console.WriteLine(student);
}
}
}
}
Output
Students:
ID: 1, Name: John Doe
ID: 3, Name: Sam Brown
ID: 4, Name: Alice Johnson
Conclusion
The List<T>
class in C# is a versatile and powerful collection that provides dynamic arrays with a rich set of methods for adding, removing, accessing, and manipulating elements. Understanding how to use List<T>
effectively is essential for managing collections of data in your applications. By leveraging the capabilities of List<T>
, you can write more efficient and maintainable C# code.