C# List 泛型值的遍历
时间: 2023-09-01 19:13:00 浏览: 186
使用 foreach 循环可以遍历 C# 中的 List 泛型值。以下是一个示例代码:
```
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
foreach (int number in numbers)
{
Console.WriteLine(number);
}
```
在此示例中,我们创建了一个 List<int> 对象,并向其添加了三个整数。然后我们使用 foreach 循环遍历该 List 对象中的值,并将每个值打印到控制台上。
相关问题
c# 编写泛型list方法
下面是一个示例代码,演示了如何在C#中编写一个泛型List方法:
```csharp
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
// 创建一个整数类型的List
List<int> numbers = new List<int>();
// 添加一些数据
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// 调用泛型List方法
PrintList(numbers);
}
// 泛型List方法
static void PrintList<T>(List<T> list) {
foreach (T item in list) {
Console.WriteLine(item);
}
}
}
```
在上面的代码中,我们首先创建了一个整数类型的List,并向其中添加了一些数据。然后,我们调用了一个名为PrintList的泛型List方法,该方法接受一个List<T>类型的参数,并使用foreach循环遍历列表中的每个元素,将其输出到控制台上。由于PrintList方法是一个泛型方法,它可以接受任何类型的List作为参数。
c# list 遍历
### 遍历C#中的列表
在C#中,`foreach`循环是一种常用的方式来迭代集合中的项。这不仅限于数组,还可以用于各种类型的集合,比如`ArrayList`、`HashTable`以及泛型集合[^3]。
下面是一个具体的例子来展示如何使用`foreach`遍历一个整数列表:
```csharp
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int>{1, 2, 3, 4, 5};
foreach (int number in numbers) {
Console.WriteLine(number);
}
}
}
```
这段代码会依次打印出列表里的每一个数字。这里创建了一个名为`numbers`的整数列表,并通过`foreach`语句逐一遍历其中的元素并输出到控制台。
对于更复杂的数据结构或当需要访问索引时,则可以考虑其他方式如`for`循环或者LINQ查询表达式。但是,在大多数情况下,如果只是简单地读取每个项目而不需要知道其位置的话,`foreach`是最简洁的选择之一。
阅读全文
相关推荐
















