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 methodnumbers.Add(10);numbers.Add(20);numbers.Add(30);Console.WriteLine("After adding elements:");foreach (var num in numbers){Console.WriteLine(num);}// AddRange methodvar 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
numbersthat can store integers (inttype).Lines 11–13: We use the
Addmethod of theList<int>class to add integers10,20, and30to thenumberslist.Lines 15–18: We use a
foreachloop that iterates over each element (num) in thenumberslist and prints each element to the console usingConsole.WriteLine.Line 21: We declare and initialize a new list named
moreNumberswith elements40and50using the collection initializer syntax.Line 22: We use the
AddRangemethod of theList<int>class to add all elements from themoreNumberslist to the end of thenumberslist.
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. Thecountparameter 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 methodnumbers.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 methodnumbers.Remove(20);Console.WriteLine("After removing element 20:");foreach (var num in numbers){Console.WriteLine(num);}// RemoveAt methodnumbers.RemoveAt(2); // Removes element at index 2Console.WriteLine("After removing element at index 2:");foreach (var num in numbers){Console.WriteLine(num);}// RemoveRange methodnumbers.RemoveRange(1, 2); // Removes 2 elements starting from index 1Console.WriteLine("After removing range of elements:");foreach (var num in numbers){Console.WriteLine(num);}// RemoveAll methodnumbers.RemoveAll(n => n > 30); // Removes all elements greater than 30Console.WriteLine("After removing elements greater than 30:");foreach (var num in numbers){Console.WriteLine(num);}}}
Explanation
Line 23: We use the
Removemethod of theList<int>class to remove the first occurrence of the integer20from thenumberslist.Line 31: We use the
RemoveAtmethod of theList<int>class to remove the element at index2from thenumberslist.Line 39: We use the
RemoveRangemethod of theList<int>class to remove two elements starting from index1in thenumberslist.Line 47: We use the
RemoveAllmethod of theList<int>class with a lambda expression to remove all elements greater than30from thenumberslist.
Searching and sorting
Contains(T item): This function checks whether a particular item exists in the list. It returnstrueif the item is present; otherwise, it returnsfalse.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 methodnumbers.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 methodbool contains20 = numbers.Contains(20);Console.WriteLine($"List contains 20: {contains20}");// IndexOf methodint index30 = numbers.IndexOf(30);Console.WriteLine($"Index of 30: {index30}");// Sort methodnumbers.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
Containsmethod of theList<int>class to check if the list contains the integer20. The result (trueorfalse) is stored in the variablecontains20.Line 27: We use the
IndexOfmethod of theList<int>class to find the index of the first occurrence of the integer30in thenumberslist. The index is stored in the variableindex30.Line 31: We use the
Sortmethod of theList<int>class to sort the elements in thenumberslist in ascending order.Line 39: We use the
BinarySearchmethod of theList<int>class to perform a binary search on the sortednumberslist to find the index of the integer30. The index is stored in thesearchIndexvariable.
Accessing elements
Item[int index]orlist[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 methodnumbers.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 indexConsole.WriteLine($"Element at index 0: {numbers[0]}");// Count propertyint count = numbers.Count;Console.WriteLine($"Number of elements: {count}");}}
Explanation
Line 23: We use index access (
[]notation) to retrieve and print the element at index0of thenumberslist.Line 26: We use the
Countproperty of theList<int>class to get the number of elements in thenumberslist and stores it in the variablecount.
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 methodnumbers.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 methodint[] array = new int[numbers.Count];numbers.CopyTo(array, 0);Console.WriteLine("Copied array:");foreach (var num in array){Console.WriteLine(num);}// Clear methodnumbers.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
arraywith the same length as thenumberslist, then use theCopyTomethod of theList<int>class to copy all elements from thenumberslist to thearraystarting at index0.Line 32: We use the
Clearmethod of theList<int>class to remove all elements from thenumberslist.
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.
Free Resources