【问题标题】:Is there a simpler way to cycle back to the start of a list?有没有更简单的方法可以循环回到列表的开头?
【发布时间】:2020-09-11 03:40:09
【问题描述】:

我有以下代码:

int index = currentIndex;
do
{
    if (index == list.Count - 1)
    {
        // At the end, cycle round to the start
        index = -1;
    }

    index++;
}
while (list[index] satisfies some condition);

// Do something with list[index]

currentIndex = index;

这显然有效,而且效率并不低。

但是,这段代码被调用了好几次,我想知道它是否可以通过某种方式变得更高效或更简洁。

【问题讨论】:

  • 我认为这取决于您在循环中所做的事情,这将决定如何使索引回到-1。你能不循环列表本身,这样你就不必重置索引吗?
  • @Jawad 这是通过系统调用获得的文件夹/目录名称列表。我可以把它放到一个链表中,但我不确定这会更快。

标签: c# arrays loops while-loop


【解决方案1】:

如果列表非空,您可以使用remainder operator:

index = index % list.Count

至于效率,需要进行基准测试。

UPD

正如Šimon Kocúrek 在 cmets 中所说,您可以将增量和提醒合并为一个操作:

index = (index + 1) % list.Count

【讨论】:

  • 这是干净的解决方案。 (也可以改进为index = (index + 1) % list.Count)。至于效率,这是尽可能简单和高效的。如果这是瓶颈,你应该想办法完全不这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
相关资源
最近更新 更多