简体   繁体   中英

Efficient collection for inserts and removals at the beginning

What collection would you recommend for a code that frequently inserts and removes objects at the beginning of the collection only.

Here is some code to illustrate my requirements

while (collection.Count != 0)
{
   object obj = collection[0];
   collection.RemoveAt(0);

   ...

   if (somethingWith(obj))
       collection.Insert(0, anotherObj);

   ...  
}

There is no inserts or removals at positions other than 0. Collection is not sorted.

What would you recommend?

EDIT:

I don't really need to do anything fancy with the collection. The collection is used to queue objects that should be processed (and collection gets populated during processing).

It seems you only want to implement a LIFO container, so you can use a Stack<T> :

while (stack.Count > 0) {
    object obj = stack.Pop();
    // ...
    if (SomethingWith(obj)) {
        stack.Push(anotherObj);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM