簡體   English   中英

有沒有更簡單的方法可以循環回到列表的開頭?

[英]Is there a simpler way to cycle back to the start of a list?

我有以下代碼:

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;

這顯然有效,而且效率並不低。

但是,這段代碼被調用了好幾次,我想知道它是否可以通過某種方式變得更高效或更簡潔。

如果列表非空,您可以使用余數運算符

index = index % list.Count

至於效率,需要對標。

UPD

正如Šimon Kocúrek在評論中所說,您可以將增量和提醒合並到一個操作中:

index = (index + 1) % list.Count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM