便宜VPS主机精选
提供服务器主机评测信息

c#中使用for循环高效处理集合的技巧详解

是的,C# 的 for 循环可以处理集合(Collection)。在 C# 中,集合通常是一个实现了 IEnumerableIEnumerator 接口的类,例如 List<T>Dictionary<TKey, TValue>HashSet<T> 等。

以下是一些使用 for 循环遍历集合的示例:

  1. 遍历 List<int>
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Count; i++)
{
    Console.WriteLine(numbers[i]);
}
  1. 遍历 Dictionary<string, int>
Dictionary<string, int> fruits = new Dictionary<string, int>
{
    { "apple", 5 },
    { "banana", 8 },
    { "orange", 3 }
};

foreach (KeyValuePair<string, int> fruit in fruits)
{
    Console.WriteLine($"{fruit.Key}: {fruit.Value}");
}

注意:虽然这里使用了 foreach 循环,但它实际上是遍历集合的一种简便方法。实际上,foreach 循环底层也是使用 for 循环来遍历集合。因此,你可以根据需要选择使用 for 循环或 foreach 循环来遍历集合。

未经允许不得转载:便宜VPS测评 » c#中使用for循环高效处理集合的技巧详解