c# Adding a Remove(int index) method to the .NET Queue class

前端 未结 12 1639
攒了一身酷
攒了一身酷 2021-01-07 17:14

I would like to use the generic queue class as described in the .NET framework (3.5) but I will need a Remove(int index) method to remove items from the queue. Can I achieve

12条回答
  •  情歌与酒
    2021-01-07 17:30

    Although there isn't a built-in way, you shouldn't use a List structure or other structure, IFF RemoveAt isn't a frequent operation.

    If you are normally enqueuing and dequeuing but only occasionally removing, then you should be able to afford a queue rebuild when removing.

    public static void Remove(this Queue queue, T itemToRemove) where T : class
    {
        var list = queue.ToList(); //Needs to be copy, so we can clear the queue
        queue.Clear();
        foreach (var item in list)
        {
            if (item == itemToRemove)
                continue;
    
            queue.Enqueue(item);
        }
    }
    
    public static void RemoveAt(this Queue queue, int itemIndex) 
    {
        var list = queue.ToList(); //Needs to be copy, so we can clear the queue
        queue.Clear();
    
        for (int i = 0; i < list.Count; i++)
        {
            if (i == itemIndex)
                continue;
    
            queue.Enqueue(list[i]);
        }
    }
    

    The following approach might be more efficient, using less memory, and thus less GC:

    public static void RemoveAt(this Queue queue, int itemIndex)
    {
        var cycleAmount = queue.Count;
    
        for (int i = 0; i < cycleAmount; i++)
        {
            T item = queue.Dequeue();
            if (i == itemIndex)
                continue;
    
            queue.Enqueue(item);
        }
    }
    

提交回复
热议问题