Curriculum
List
is a class in C# that represents a generic collection of objects, similar to an array but with additional functionality. Here’s an example of using List
to store and manipulate a collection of integers:
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Create a List of integers List<int> numbers = new List<int>(); // Add some numbers to the list numbers.Add(1); numbers.Add(2); numbers.Add(3); // Display the contents of the list Console.WriteLine("Numbers in list:"); foreach (int number in numbers) { Console.WriteLine(number); } // Insert a number at a specific index numbers.Insert(1, 5); // Remove a number from the list numbers.Remove(3); // Sort the list numbers.Sort(); // Display the sorted list Console.WriteLine("Numbers in sorted list:"); foreach (int number in numbers) { Console.WriteLine(number); } } }
In this example, we first create an empty List<int>
object called numbers
. We then add some integers to the list using the Add
method. We use a foreach
loop to display the contents of the list.
Next, we use the Insert
method to insert the number 5 at index 1 in the list. We then use the Remove
method to remove the number 3 from the list. Finally, we use the Sort
method to sort the list in ascending order.
We then use another foreach
loop to display the contents of the sorted list.
Here are some other useful methods provided by the List
class:
Count
: Returns the number of elements in the list.Contains
: Determines whether an element is in the list.IndexOf
: Returns the index of the first occurrence of an element in the list.Clear
: Removes all elements from the list.ToArray
: Copies the elements of the list to a new array.Here’s an example that demonstrates some of these methods:
// Create a List of strings List<string> colors = new List<string>(); colors.Add("red"); colors.Add("green"); colors.Add("blue"); // Check if a color is in the list if (colors.Contains("green")) { Console.WriteLine("Green is in the list"); } // Find the index of a color in the list int index = colors.IndexOf("blue"); Console.WriteLine("Blue is at index {0}", index); // Remove a color from the list colors.Remove("green"); // Convert the list to an array string[] colorArray = colors.ToArray();
It’s important to note that List
provides many other useful properties and methods for working with collections, such as AddRange
to add a collection of elements to the list, RemoveAt
to remove an element at a specific index, and GetEnumerator
to get an enumerator that iterates through the list.