C#中用foreach、for循环遍历多组并行数组实现逐位元素对应输出
C# 多数组同索引拼接输出实现
前置提示:示例中四个数组长度完全相等,实际项目编码时一定要先校验所有待拼接数组的长度一致,否则运行时会抛出索引越界异常。
for循环实现
for循环依托整数索引作为遍历游标,是该场景下最直观的实现方式:
// 前置长度校验 if (name.Length != family.Length || name.Length != number.Length || name.Length != age.Length) { throw new InvalidOperationException("参与拼接的数组长度必须保持一致"); } // 按索引遍历基准数组 for (int i = 0; i < name.Length; i++) { // 提取同索引位置的元素拼接为单行输出 Console.WriteLine($"{name[i]} {family[i]} {number[i]} {age[i]}"); }
foreach循环实现
foreach循环本身不会暴露遍历过程中的索引值,因此需要手动维护一个索引计数器,用来同步定位其余数组的同位置元素:
// 前置长度校验和for循环逻辑一致 if (name.Length != family.Length || name.Length != number.Length || name.Length != age.Length) { throw new InvalidOperationException("参与拼接的数组长度必须保持一致"); } int currentIndex = 0; // 以name数组为遍历基准执行foreach foreach (var nameItem in name) { // 用维护的索引提取其余数组的同位置元素 Console.WriteLine($"{nameItem} {family[currentIndex]} {number[currentIndex]} {age[currentIndex]}"); // 每轮循环结束后累加索引,匹配下一轮的元素位置 currentIndex++; }
补充:如果使用.NET 6及以上版本,可以借助LINQ的带索引重载实现不需要手动维护计数器的foreach逻辑:
name.Select((value, index) => new { value, index }) .ToList() .ForEach(item => Console.WriteLine($"{item.value} {family[item.index]} {number[item.index]} {age[item.index]}") );
内容的提问来源于stack exchange,提问作者NeonX
相关产品推荐
相关产品推荐

