You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现指定整数序列的固定顺序循环遍历?

实现固定顺序循环遍历整数变量

核心思路很简单:先把变量按你需要的顺序存入数组,然后维护一个索引计数器,每次取当前索引的元素后,将索引自增并对数组长度取模,就能自动实现循环回到开头的效果。

方法一:基础循环实现(适合单次批量遍历)

直接用计数器控制索引,遍历指定次数:

int A = 20;
int B = 10;
int C = 40;
int D = 5;

// 按目标顺序初始化数组
var orderedSequence = new[] { A, B, C, D };
int currentIndex = 0;

// 示例:遍历10次验证循环效果
for (int i = 0; i < 10; i++)
{
    int currentValue = orderedSequence[currentIndex];
    Console.WriteLine(currentValue); // 输出顺序:20 → 10 → 40 → 5 → 20 → 10 → 40 → 5 → 20 → 10
    
    // 更新索引,到达数组末尾后重置为0
    currentIndex = (currentIndex + 1) % orderedSequence.Length;
}

方法二:迭代器实现(可复用的循环序列)

如果需要多次复用这个循环遍历逻辑,可以写一个迭代器方法,生成无限循环的序列,按需取用:

int A = 20;
int B = 10;
int C = 40;
int D = 5;
var orderedSequence = new[] { A, B, C, D };

// 定义迭代器,无限返回顺序循环的元素
IEnumerable<int> GetCyclicSequence(int[] sequence)
{
    int index = 0;
    while (true)
    {
        yield return sequence[index];
        index = (index + 1) % sequence.Length;
    }
}

// 使用示例:取前8个元素
foreach (var num in GetCyclicSequence(orderedSequence).Take(8))
{
    Console.WriteLine(num); // 输出顺序:20 → 10 → 40 → 5 → 20 → 10 → 40 → 5
}

这两种方式都能严格遵循你要求的固定顺序循环,不会出现随机重复的问题。

内容的提问来源于stack exchange,提问作者Okta Vio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:32:50