在C#中,可以使用foreach循环遍历两个列表。以下是一个示例代码:
List list1 = new List { 1, 2, 3, 4, 5 };
List list2 = new List { 6, 7, 8, 9, 10 };
// 方法一:使用foreach循环遍历
foreach (int item in list1.Concat(list2))
{
Console.WriteLine(item);
}
// 方法二:使用for循环遍历
int count = list1.Count > list2.Count ? list1.Count : list2.Count;
for (int i = 0; i < count; i++)
{
if (i < list1.Count)
{
Console.WriteLine(list1[i]);
}
if (i < list2.Count)
{
Console.WriteLine(list2[i]);
}
}
在这个示例中,我们有两个列表list1和list2。我们可以使用foreach循环遍历list1.Concat(list2)
来遍历两个列表的合并结果。Concat
方法用于将两个列表连接在一起。
另外,我们也可以使用for循环来遍历两个列表。我们首先获取两个列表中较大的一个的元素数量作为循环的次数。然后使用索引来访问列表的元素,并在索引小于列表长度的情况下打印元素。
这两种方法都可以高效地遍历两个列表。具体使用哪种方法取决于你的需求和个人偏好。