C# 遍历

在C#中,您可以使用多种方式来遍历数据结构,如数组、列表、字典等。以下是几种常见的方法:

  1. 使用for循环遍历数组或列表:
int[] numbers = {1, 2, 3, 4, 5}; 
 for (int i = 0; i < numbers.Length; i++)  {    
   Console.WriteLine(numbers[i]); 
  }

或者使用foreach循环:

int[] numbers = {1, 2, 3, 4, 5};   
   foreach (int number in numbers)  {     
    Console.WriteLine(number);
   }
  1. 使用foreach循环遍历字典:
Dictionary<string, int> dictionary = new Dictionary<string, int>()   {       
 {"apple", 1 },    {"banana", 2 },    {"cherry", 3 }  
  };   
   foreach (KeyValuePair<string, int> pair in dictionary)  {       
    Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}"); 
  }
  1. 使用LINQ查询遍历数据:

C#中的LINQ(Language-Integrated Query)语言集成查询功能可以使遍历数据变得更加简单和强大。例如,您可以使用它筛选出列表中的偶数:

List<int> numbers = new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 
var evenNumbers = from num in numbers      
where num % 2 == 0        
select num;     
 foreach (int num in evenNumbers)  
 {       
    Console.WriteLine(num); 
  }
### C#遍历列表、数组和集合的方法 #### 遍历数组 在 C# 中,可以使用 `foreach` 循环轻松遍历一维数组。以下是具体示例: ```csharp using System; class Program { static void Main(string[] args) { // 定义并初始化一维数组 int[] array = { 1, 2, 3, 4, 5 }; // 使用 foreach 遍历数组 foreach (int number in array) { Console.WriteLine(number); } } } ``` 此代码片段展示了一种简单的方式通过 `foreach` 来访问数组中的每一个元素[^4]。 #### 遍历列表 对于动态数组(即 `List<T>`),同样可以通过 `foreach` 进遍历。以下是一个具体的例子: ```csharp using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // 初始化一个整型列表 List<int> list = new List<int>() { 10, 20, 30, 40 }; // 使用 foreach 遍历列表 foreach (int item in list) { Console.WriteLine(item); } } } ``` 这段代码说明了如何利用 `List<T>` 的灵活性以及其支持的迭代方式[^3]。 #### 遍历集合 当涉及到更复杂的集合类型时,比如字典 (`Dictionary<TKey,TValue>`) 或双向链表 (`LinkedList<T>`) ,仍然能够采用类似的机制完成遍历工作。这里提供两个实例分别针对这两种情况: ##### 字典遍历 ```csharp using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // 创建一个键值对形式的字典 Dictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary.Add(1, "Apple"); dictionary.Add(2, "Banana"); // 遍历字典项 foreach (KeyValuePair<int, string> pair in dictionary) { Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}"); } } } ``` 该部分解释了怎样逐一读取存储于字典内的每一对关联数据[^5]。 ##### 双向链表遍历 ```csharp using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // 构建一个字符串类型的双向链表 LinkedList<string> linkedList = new LinkedList<string>(new [] {"Red", "Green", "Blue"}); // 输出节点内容 foreach (var color in linkedList){ Console.WriteLine(color); } } } ``` 这一节演示了有关双向链接的数据结构及其基本操作之一——遍历过程。 ### 总结 以上介绍了几种常见容器对象在 C# 下的不同遍历手段,无论是基础的一维数组还是高级别的泛型集合类都具备良好的可扩展性和易用性特点。开发者可根据实际需求选取合适的解决方案来进相应的编程实践。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值