Evo*_*lor 3 c# iteration queue list repeat
我有一个这样的列表:
List<Thing> foo = new List<Thing>();
foo.PopulateWithFourThings();
Run Code Online (Sandbox Code Playgroud)
我想一遍又一遍地遍历它,比如0123012301230123 ......
Foreach不是我想要的,因为我不想一切都在同一时间.我一直在搞乱队列,我想知道队列是否适合这里?或者,如果有比Queues更好的东西.
我正在寻找这种情况下最好的代码实践(反复遍历列表).
那么有更好的选择:
if (nextElementIsNeeded)
{
Thing thing = foo[0];
foo.RemoveAt(0);
foo.Add(thing);
return thing;
}
Run Code Online (Sandbox Code Playgroud)
或者使用队列的以下代码:
Queue<Thing> foo = new Queue<Thing>();
foo.PopulateWithForThings();
//////////////////////////////////////
if (nextElementIsNeeded)
{
Thing thing = foo.Dequeue();
foo.Enqueue(thing);
return thing;
}
Run Code Online (Sandbox Code Playgroud)
而不是不断地向集合中添加和从集合中删除相同的项目(无论哪种类型),只需使用循环索引来访问您拥有的列表.
int currentElementIndex = 0;
//..
if (nextElementIsNeeded)
{
currentElementIndex = (currentElementIndex + 1) % foo.Count;
thing = foo[currentElementIndex];
}
Run Code Online (Sandbox Code Playgroud)