Lists in C# are important data structures that allow developers to store, manage, and manipulate collections of items. They do provide a dynamic, resizeable, and strongly-typed alternative to arrays.
But, what makes Lists so important in C#?
Lists in C# play a crucial role in managing collections of data and are commonly used in various applications, so here are some reasons why lists are important in C#:
- Dynamic Size – Lists in C# have a dynamic size, meaning that you can add or remove elements as needed without having to worry about the size of the list.
- Strongly Typed – Lists enforce type safety, meaning that they store items of a specific type, and any attempt to add an item of a different type will result in a compile-time error.
- Performance – Lists are optimized for performance, providing fast and efficient access to elements in the list.
- Interoperability – Lists can be used with LINQ (Language Integrated Query) to perform complex queries and operations on collections.
Lists in C# are part of System.Collections.Generic namespace. They offer a lot of methods and properties that you can use. Below are some common methods that can be used on a List in C#, along with examples, outputs, and descriptions:
Add() method
The Add() method is used to add an item to the end of a List. Example:
List<int> numbers = new List<int> {1, 2, 3}; numbers.Add(4); Console.WriteLine(string.Join(",", numbers)); //Output: 1,2,3,4
Insert() method
The Insert() method is used to insert an item at a specified index in a List.
Example:
List<int> numbers = new List<int> {1, 2, 3}; numbers.Insert(0, 0); Console.WriteLine(string.Join(",", numbers)); //Output: 0,1,2,3
Remove() method
The Remove() method is used to remove an item from a List.
Example:
List<int> numbers = new List<int> {1, 2, 3}; numbers.Remove(2); Console.WriteLine(string.Join(",", numbers)); //Output: 1,3
RemoveAt() method
The RemoveAt() method is used to remove an item at a specified index in a List.
List<int> numbers = new List<int> {1, 2, 3}; numbers.RemoveAt(1); Console.WriteLine(string.Join(",", numbers)); //Output: 1,3
Count property
The Count property is used to get the number of items in a List.
List<int> numbers = new List<int> {1, 2, 3}; Console.WriteLine(numbers.Count); //Output: 3
IndexOf() method
The IndexOf() method is used to get the index of an item in a List.
List<int> numbers = new List<int> {1, 2, 3}; Console.WriteLine(numbers.IndexOf(2)); //Output: 1
Sort() method
The Sort() method is used to sort the items in a List in ascending order.
List<int> numbers = new List<int> {3, 1, 2}; numbers.Sort(); Console.WriteLine(string.Join(",", numbers)); //Output: 1,2,3
Image by rawpixel.com on Freepik