Data Structures

C# Lists

Working with Lists

C# lists use List<T> for dynamic typed collections.

Introduction to C# Lists

C# Lists are part of the System.Collections.Generic namespace and provide a way to store collections of objects dynamically. Unlike arrays, which have a fixed size, lists can grow and shrink in size automatically as elements are added or removed. Lists are implemented using the generic List<T> class, where T represents the type of elements in the list.

Creating a List

To create a list, you first need to specify the type of elements it will hold. Here's a simple example of creating a list of integers:

Adding Elements to a List

Once a list is created, you can add elements to it using the Add method. The Add method appends an element to the end of the list:

Accessing Elements

Elements in a list can be accessed by their index, similar to arrays. Here is how you can access the first element:

Iterating Over a List

You can iterate over the elements of a list using a foreach loop. This is a convenient way to access each element without needing to know the size of the list:

Removing Elements from a List

Elements can be removed from a list using the Remove method, which removes the first occurrence of a specific value:

Finding Elements

The List<T> class provides several methods to find elements, such as Contains and Find. The Contains method checks if an element exists in the list:

The Find method can be used to locate the first element that matches a specified condition:

Sorting a List

Lists can be sorted using the Sort method. By default, this sorts the elements in ascending order:

Conclusion

C# Lists provide a powerful and flexible way to work with collections of data. They are dynamic, type-safe, and offer a range of methods for manipulation, making them an essential tool in any C# programmer's toolkit.

Previous
Arrays