Skip to main content

List Methods

Introduction

In C#, List<T> is one of the most useful data types in the .NET framework. It represents a strongly typed list of objects that can be accessed by index. It provides methods to search, sort, and manipulate lists. In this tutorial, we will explore various methods provided by the List<T> class.

Creating a List

First, we need to know how to create a List. Here's a simple example of how to declare a list of integers:

List<int> numbers = new List<int>();

In this line of code, int is the type of elements in the list, and numbers is the name of the list.

We can add elements to the list using the Add method:

numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

Now, our list numbers has three elements: 1, 2, and 3.

Common List Methods

Add

As we've seen, the Add method appends an element to the end of the list.

List<int> numbers = new List<int>();
numbers.Add(1); // numbers: {1}
numbers.Add(2); // numbers: {1, 2}
numbers.Add(3); // numbers: {1, 2, 3}

AddRange

If you want to add multiple elements at once, you can use the AddRange method, which takes an IEnumerable as a parameter:

List<int> moreNumbers = new List<int>(){4, 5, 6};
numbers.AddRange(moreNumbers); // numbers: {1, 2, 3, 4, 5, 6}

Clear

The Clear method removes all elements from the list:

numbers.Clear();  // numbers: {}

Contains

The Contains method checks if a certain element exists in the list:

bool containsTwo = numbers.Contains(2);  // containsTwo: true

Remove

The Remove method removes the first occurrence of a specific object from the list:

numbers.Remove(2);  // numbers: {1, 3}

IndexOf

The IndexOf method returns the index of the first occurrence of a value in the list:

int index = numbers.IndexOf(3);  // index: 1

Count

The Count property gets the number of elements in the list:

int count = numbers.Count;  // count: 2

Conclusion

In this tutorial, we discussed some of the most common methods offered by the List<T> class in C#. There are many more methods provided by this class that can help you manipulate lists in various ways. Practice using these methods and try to find more methods to solve different problems. Happy coding!