简体   繁体   中英

C# List RemoveAt(0)

I have a list and want to iterate smoothly through it while removing one element after another. I thought I could do it like this:

    List<Point> open = new List<Point>();
...            
while (!(open == null))
            {
                Point p = open.RemoveAt(0);
...

However, it is not quite working how I would like it to, starting with "Cannot implicitly convert type 'void' to 'Point'". But shouldn't the call of RemoveAt give the point to P before removing it/making it void?

List.RemoveAt does not return item which you are removing. Also list will not become null when you'll remove all items. It will become empty, ie with Count equal to 0 . I would suggest you to use Queue<T> instead of List<T> . Thus you will be able to remove fist added item and get it at same time:

Queue<Point> open = new Queue<Point>();

while(open.Count > 0)
{
    var point = open.Dequeue();
    // ...
}

If you want to use list, and remove first items, then you should retrieve item by index, and only then remove it from list:

List<Point> open = new List<Point>();

while (open.Count > 0) // or open.Any()
{
    Point p = open[0];
    open.RemoveAt(0);
    // ...
}

No, it does not. It does not return anything, as per the specification . Try using a Queue<Point> instead. Also, removing the first item in a List<T> does force a copy of the array-contents as far as I know (If somebody knows, please add relevant reference), so always avoid removing the first element in list and try to always find the best data structure to solve your particular issue!

Example:

var open = new Queue<Point>();
// ... Fill it
// Any() is in general faster than Count() for checking that collection has data
// It is a good practice to use it in general, although Count (the property) is as fast
// but not all enumerables has that one
while (open.Any())     {
   Point p = open.Dequeue();
   // ... Do stuff
}

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