In C#, List<T>
is a generic class that represents a dynamic collection of elements of a specified type T
. It is part of the System.Collections.Generic
namespace.
Here’s an example of how to use List<T>
in C#:
using System; using System.Collections.Generic; class Program { static void Main() { // Create a new List of integers List<int> numbers = new List<int>(); // Add elements to the list numbers.Add(10); numbers.Add(20); numbers.Add(30); // Access elements by index Console.WriteLine(numbers[0]); // Output: 10 // Modify elements numbers[1] = 25; // Remove elements numbers.Remove(30); // Iterate over the list foreach (int number in numbers) { Console.WriteLine(number); } // Check if an element exists in the list bool contains = numbers.Contains(20); Console.WriteLine(contains); // Output: True // Get the number of elements in the list int count = numbers.Count; Console.WriteLine(count); // Output: 2 // Clear all elements from the list numbers.Clear(); Console.WriteLine(numbers.Count); // Output: 0 } }
In the example above, we create a List<int>
called numbers
and perform various operations such as adding elements, accessing elements by index, modifying elements, removing elements, iterating over the list, checking for the existence of an element, getting the count of elements, and clearing the list.
Note that List<T>
provides many more methods and properties for manipulating and querying collections. You can refer to the official documentation for more information: List<T> Class (System.Collections.Generic)
C# List<T> example using collection initializer:
Certainly! In C#, you can use a collection initializer to initialize a List<T>
with elements directly. Here’s an example:
using System; using System.Collections.Generic; class Program { static void Main() { // Create a new List of strings using a collection initializer List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; // Iterate over the list and print the names foreach (string name in names) { Console.WriteLine(name); } } }
In this example, we declare a List<string>
called names
and initialize it using a collection initializer. We provide a comma-separated list of elements enclosed in curly braces {}
. The elements "Alice"
, "Bob"
, and "Charlie"
are added to the list. Then, we iterate over the list and print each name.
The output will be:
Alice Bob Charlie
Using a collection initializer is a convenient way to initialize a list with a predefined set of elements without the need to explicitly call the Add
method for each element.