What are list class methods in C#?

In C#, the List<T> class, which is found in the System.Collections.Generic namespace, is a versatile tool for managing collections of items. It provides a wide range of methods to add, remove, search, and manipulate elements within a list. Let’s dive into the various methods offered by the List<T> class to understand how they can be utilized.

Adding elements

  • Add(T item): Appends an item to the end of the list.

  • AddRange(IEnumerable<T> collection): Adds a collection of items to the end of the list.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Add method
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
Console.WriteLine("After adding elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// AddRange method
var moreNumbers = new List<int> { 40, 50 };
numbers.AddRange(moreNumbers);
Console.WriteLine("After adding range of elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
}
}

Explanation

  • Line 8: We declare and initialize a new generic list named numbers that can store integers (int type).

  • Lines 11–13: We use the Add method of the List<int> class to add integers 10, 20, and 30 to the numbers list.

  • Lines 15–18: We use a foreach loop that iterates over each element (num) in the numbers list and prints each element to the console using Console.WriteLine.

  • Line 21: We declare and initialize a new list named moreNumbers with elements 40 and 50 using the collection initializer syntax.

  • Line 22: We use the AddRange method of the List<int> class to add all elements from the moreNumbers list to the end of the numbers list.

Removing elements

  • Remove(T item): This method removes the first instance of the specified item from the list. If the item is not found, the list remains unchanged.

  • RemoveAt(int index): This function removes the item located at the specified index within the list. The index must fall within the valid range of indexes for the list.

  • RemoveRange(int index, int count): This function deletes a range of elements from the list, beginning at the specified index. The count parameter indicates the number of elements to be removed.

  • RemoveAll(Predicate<T> match): This function eliminates all elements from the list that meet the conditions set by the provided predicate. The predicate specifies the criteria for deciding which elements should be removed.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Add method
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
numbers.Add(40);
numbers.Add(50);
Console.WriteLine("After adding elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// Remove method
numbers.Remove(20);
Console.WriteLine("After removing element 20:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// RemoveAt method
numbers.RemoveAt(2); // Removes element at index 2
Console.WriteLine("After removing element at index 2:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// RemoveRange method
numbers.RemoveRange(1, 2); // Removes 2 elements starting from index 1
Console.WriteLine("After removing range of elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// RemoveAll method
numbers.RemoveAll(n => n > 30); // Removes all elements greater than 30
Console.WriteLine("After removing elements greater than 30:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
}
}

Explanation

  • Line 23: We use the Remove method of the List<int> class to remove the first occurrence of the integer 20 from the numbers list.

  • Line 31: We use the RemoveAt method of the List<int> class to remove the element at index 2 from the numbers list.

  • Line 39: We use the RemoveRange method of the List<int> class to remove two elements starting from index 1 in the numbers list.

  • Line 47: We use the RemoveAll method of the List<int> class with a lambda expression to remove all elements greater than 30 from the numbers list.

Searching and sorting

  • Contains(T item): This function checks whether a particular item exists in the list. It returns true if the item is present; otherwise, it returns false.

  • IndexOf(T item): This function provides the index of the specified item’s first occurrence in the list. If the item isn’t found, it returns -1.

  • Sort(): This method sorts the elements in the list in ascending order.

  • BinarySearch(T item): This method uses a binary search algorithm to search for a specified item in the sorted list. It returns the item’s index if found or a negative value if the item is absent.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Add method
numbers.Add(50);
numbers.Add(40);
numbers.Add(30);
numbers.Add(20);
numbers.Add(10);
Console.WriteLine("After adding elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// Contains method
bool contains20 = numbers.Contains(20);
Console.WriteLine($"List contains 20: {contains20}");
// IndexOf method
int index30 = numbers.IndexOf(30);
Console.WriteLine($"Index of 30: {index30}");
// Sort method
numbers.Sort();
Console.WriteLine("Sorted list:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// BinarySearch method (requires a sorted list)
int searchIndex = numbers.BinarySearch(30);
Console.WriteLine($"Index of 30 using BinarySearch: {searchIndex}");
}
}

Explanation

  • Line 23: We use the Contains method of the List<int> class to check if the list contains the integer 20. The result (true or false) is stored in the variable contains20.

  • Line 27: We use the IndexOf method of the List<int> class to find the index of the first occurrence of the integer 30 in the numbers list. The index is stored in the variable index30.

  • Line 31: We use the Sort method of the List<int> class to sort the elements in the numbers list in ascending order.

  • Line 39: We use the BinarySearch method of the List<int> class to perform a binary search on the sorted numbers list to find the index of the integer 30. The index is stored in the searchIndex variable.

Accessing elements

  • Item[int index] or list[index]: Retrieves or updates the element located at the specified index.

  • Count: Gets the number of elements in the list.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Add method
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
numbers.Add(40);
numbers.Add(50);
Console.WriteLine("After adding elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// Accessing elements by index
Console.WriteLine($"Element at index 0: {numbers[0]}");
// Count property
int count = numbers.Count;
Console.WriteLine($"Number of elements: {count}");
}
}

Explanation

  • Line 23: We use index access ([] notation) to retrieve and print the element at index 0 of the numbers list.

  • Line 26: We use the Count property of the List<int> class to get the number of elements in the numbers list and stores it in the variable count.

Copying and clearing

  • CopyTo(T[] array, int arrayIndex): This method will copy the elements of the list to an array.

  • Clear(): Removes all elements from the list.

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
// Add method
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
numbers.Add(40);
numbers.Add(50);
Console.WriteLine("After adding elements:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
// CopyTo method
int[] array = new int[numbers.Count];
numbers.CopyTo(array, 0);
Console.WriteLine("Copied array:");
foreach (var num in array)
{
Console.WriteLine(num);
}
// Clear method
numbers.Clear();
Console.WriteLine("List after clearing:");
foreach (var num in numbers)
{
Console.WriteLine(num); // This loop won't execute as the list is empty
}
}
}

Explanation

  • Lines 23–24: We create a new integer array called array with the same length as the numbers list, then use the CopyTo method of the List<int> class to copy all elements from the numbers list to the array starting at index 0.

  • Line 32: We use the Clear method of the List<int> class to remove all elements from the numbers list.

Conclusion

The List<T> class in C# provides an extensive set of methods for managing lists efficiently. Whether you need to add, remove, search, sort, or manipulate elements, these methods offer a robust foundation for working with collections in your C# projects. Understanding and utilizing these methods can greatly enhance your ability to handle data structures effectively.

Copyright ©2024 Educative, Inc. All rights reserved