Data Structures
.NET Lists
Working with Lists
.NET lists use List<T> for dynamic typed collections.
Introduction to .NET List<T>
The List<T> class in .NET is a part of the System.Collections.Generic
namespace and provides a dynamic collection of objects that can grow as needed. Unlike arrays, lists can be resized dynamically, making them more flexible for storing collections of objects where the size is not known at compile time.
Creating and Initializing a List
To create a list in .NET, you need to define the type of elements it will hold. This is done using the generic List class with a type parameter. Here is an example of how to create and initialize a list of integers:
Adding and Removing Elements
Lists provide several methods for adding and removing elements:
Add(T item)
: Adds an item to the end of the list.Insert(int index, T item)
: Inserts an item at the specified index.Remove(T item)
: Removes the first occurrence of the specified item.RemoveAt(int index)
: Removes the item at the specified index.
Accessing Elements in a List
You can access elements in a list using an indexer, similar to arrays. The index is zero-based, meaning the first element has an index of 0.
Here's an example of accessing elements:
Iterating Over a List
Iterating over a list is straightforward using a foreach
loop. This allows you to process each element in the list easily:
List Properties and Methods
The List<T> class provides several useful properties and methods:
Count
: Gets the number of elements contained in the list.Contains(T item)
: Checks if an item is present in the list.Clear()
: Removes all elements from the list.Sort()
: Sorts the elements in the list.
Here's a simple example:
Conclusion
The List<T> class in .NET provides a versatile way to manage collections of objects. With methods for adding, removing, and accessing elements, as well as properties like Count
and Contains
, lists are an essential part of .NET programming when dynamic collections are needed.
Data Structures
- Arrays
- Lists
- Dictionaries
- HashSets
- Previous
- Arrays
- Next
- Dictionaries