Skip to main content

Lists in C#

Getting Started with Lists in C#

C# is a popular, versatile, and powerful object-oriented programming language. One of its most important features is the ability to store, manipulate, and access data. The C# List is a frequently used data structure that can hold a collection of items. This tutorial will guide you through the fundamental concepts of Lists in C# including their creation, manipulation, and various operations.

Introduction to Lists

In C#, a List is a generic type of collection, meaning it can store any type of data such as integers, strings, objects etc. It is similar to an array but unlike arrays, lists in C# are dynamic and can grow or shrink in size automatically.

Creating a List

A List can be created in C# by using the List keyword followed by the data type of the elements enclosed in angle brackets <>. The syntax is as follows:

List<data_type> list_name = new List<data_type>();

For example, we can create a list of integers as follows:

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

Adding Elements to a List

Elements can be added to a list using the Add method. Let's add some integers to our list:

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

Accessing Elements in a List

You can access elements in a List by referring to the index number:

int firstNumber = numbers[0]; // Access the first element

Removing Elements from a List

Elements can be removed from a list using the Remove method:

numbers.Remove(2); // This will remove '2' from the list

Or you can remove an element at a specific index using the RemoveAt method:

numbers.RemoveAt(0); // This will remove the first element

Other List Operations

There are various other operations that you can perform on a list:

  • Count: Returns the number of elements in the list.
  • Sort: Sorts the elements in the list in ascending order.
  • Clear: Removes all elements from the list.
int totalElements = numbers.Count; // Get the total number of elements

numbers.Sort(); // Sort the elements

numbers.Clear(); // Remove all elements

Conclusion

This tutorial introduced you to Lists in C#, including their creation, addition and removal of elements, and various other operations. With the ability to grow and shrink dynamically, lists offer a flexible and efficient way to manage collections of data in C#. Practice what you've learned here, and you'll become proficient with Lists in C#.