Mik*_*ike 4 .net c# collections
我有一份工作清单,我正在努力工作,直到所有工作都耗尽,但不知道如何处理.我试图模仿的想法是:
foreach(Work w in _workList) {
res = DoSomethingOnWork(w);
if(res) {
_workList.Remove(w);
}
}
Run Code Online (Sandbox Code Playgroud)
原因是,在"DoSomethingForWork(w)"中,当时的工作可能不是我想要做的,所以我将跳过那个并继续下一个.当我在列表的末尾时,我想回到列表中.在我写一个集合来处理这个问题之前,我很好奇是否已经在.NET中处理这种情况了.
提前致谢!
在迭代时修改集合是非常危险的; 这样做是崩溃的秘诀.
在你的情况下,我会做的是使用队列,或者可能得到一点点发烧友并实现优先级队列.队列具有以下属性:最近添加的东西是最后一个要服务的东西,就像银行队列一样; 你加入了行的末尾,并且在你之前的每个人都得到了服务.所以你的循环看起来像这样:
while(queue.Count > 0)
{
var currentCustomer = queue.Dequeue();
bool success = ServiceCustomer(currentCustomer);
if (!success)
{
// the customer couldn't be serviced. Send them to the
// back of the line so that we service other customers before
// trying again.
queue.Enqueue(currentCustomer);
}
}
Run Code Online (Sandbox Code Playgroud)
PriorityQueue的工作方式与队列类似,只是每个任务都获得与之关联的优先级.优先级较高的任务可以成为VIP,并将队列跳转到优先级较低的任务之前.实现自己的优先级队列并不太难.
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |