C# List
In C#, a List is a dynamic data structure from the System.Collections.Generic
namespace that allows you to store a collection of elements. Unlike arrays, a list can grow or shrink in size automatically as you add or remove items, making it a flexible option for working with collections of data.
Key Features of a List in C#
- Dynamic size: Unlike arrays, lists can automatically adjust their size when elements are added or removed.
- Generic: Lists are part of the
System.Collections.Generic
namespace, which means they can be strongly typed to store elements of a specific type (e.g.,List<int>
,List<string>
). - Index-based: Similar to arrays, you can access elements by their index.
Defining a List
You can define a list to store elements of any type. The T
in List<T>
is the type of elements the list will store.
For example, a list of integers:
Or a list of strings:
Adding Elements to a List
You can use the Add()
method to add elements to a list:
Accessing Elements
You can access elements by their index, just like with arrays:
Modifying Elements
You can modify elements by specifying their index:
Removing Elements
Remove(): Removes the first occurrence of a specific value from the list.
RemoveAt(): Removes the element at the specified index.
Clear(): Removes all elements from the list.
Checking List Size
You can use the Count
property to check how many elements are in the list:
Iterating Through a List
You can use a for
loop or a foreach
loop to iterate through the elements in a list:
Common List Methods in C#
- Add(T item): Adds an element to the end of the list.
- AddRange(IEnumerable<T> collection): Adds the elements of a collection to the end of the list.
- Insert(int index, T item): Inserts an element at the specified index.
- Remove(T item): Removes the first occurrence of the specified element.
- RemoveAt(int index): Removes the element at the specified index.
- Clear(): Removes all elements from the list.
- Contains(T item): Determines whether the list contains a specific value.
- IndexOf(T item): Returns the index of the first occurrence of the specified value.
- Sort(): Sorts the elements of the list.
- Reverse(): Reverses the order of the elements in the list.
Example of List in C#
Summary
- List<T> is a dynamic array-like data structure in C# that automatically resizes when elements are added or removed.
- It supports operations like adding, removing, sorting, and searching for elements.
- You can create a list for any data type (int, string, custom objects) using the generic
List<T>
class.