C# List<T> 类用于存储和获取元素。它可以有重复的元素。它位于 System.Collections.Generic 命名空间中。
让我们看一个通用 List<T> 类的示例,它使用 Add() 方法存储元素并使用 for-each 循环迭代列表。
using System;
using System.Collections.Generic;
public class ListExample
{
public static void Main(string[] args)
{
// Create a list of strings
var names = new List<string>();
names.Add("Sonoo Jaiswal");
names.Add("Ankit");
names.Add("Peter");
names.Add("Irfan");
// Iterate list element using foreach loop
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}输出:
Sonoo Jaiswal Ankit Peter Irfan
using System;
using System.Collections.Generic;
public class ListExample
{
public static void Main(string[] args)
{
// Create a list of strings using collection initializer
var names = new List<string>() {"Sonoo", "Vimal", "Ratan", "Love" };
// Iterate through the list.
foreach (var name in names)
{
Console.WriteLine(name);
}
}
}输出:
Sonoo Vimal Ratan Love