遍历 C# 中的列表
 
本教程将讨论在 C# 中遍历列表的方法。
使用 C# 中的 for 循环遍历列表
    
for 循环在 C# 中重复一段指定时间的代码块。我们可以使用 for 循环遍历 C# 中的列表。请参见以下示例。
using System;
using System.Collections.Generic;
namespace iterate_through_a_list {
  class Program {
    static void Main(string[] args) {
      List<string> values = new List<string> { "value1", "value2", "value3" };
      for (int i = 0; i < values.Count; i++) {
        Console.WriteLine("Element#{0} = {1}", i, values[i]);
      }
    }
  }
}
输出:
Element#0 = value1
Element#1 = value2
Element#2 = value3
我们初始化了包含字符串值的列表值,并使用 C# 中的 for 循环遍历值。我们将 values.Count 属性用作循环的上限,并打印了所有 values 列表元素。
使用 C# 中的 foreach 循环遍历列表
    
foreach 循环遍历 C# 中的数据结构。foreach 循环用作迭代器,因为它为数据结构中的每个元素重复一个代码块。我们还可以使用 foreach 循环遍历列表。以下代码示例向我们展示了如何使用 C# 中的 foreach 循环遍历列表。
using System;
using System.Collections.Generic;
namespace iterate_through_a_list {
  class Program {
    static void Main(string[] args) {
      List<string> values = new List<string> { "value1", "value2", "value3" };
      foreach (var v in values) {
        Console.WriteLine("Element = {0}", v);
      }
    }
  }
}
输出:
Element = value1
Element = value2
Element = value3
我们初始化了包含字符串值的列表值,并使用 C# 中的 foreach 循环遍历值。我们不必在 foreach 循环中指定任何上限。它会自动循环遍历 C# 中数据结构的每个元素。
使用 C# 中的 Lambda 表达式遍历列表
为了使我们的代码更简洁,我们还可以使用 lambda 表达式来迭代 C# 中的列表。lambda 表达式在 C# 中创建匿名函数。我们可以创建一个匿名函数,该函数使用 C# 中的 lambda 表达式遍历列表。以下代码示例向我们展示了如何使用 C# 中的 lambda 表达式遍历列表
using System;
using System.Collections.Generic;
namespace iterate_through_a_list {
  class Program {
    static void Main(string[] args) {
      List<string> values = new List<string> { "value1", "value2", "value3" };
      values.ForEach((v) => Console.WriteLine("Element = {0}", v));
    }
  }
}
输出:
Element = value1
Element = value2
Element = value3
在上面的代码中,我们初始化了包含字符串值的列表值,并使用 C# 中的 lambda 表达式遍历值。lambda 表达式将我们的迭代代码减少到仅一行。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn