modify an element in a queue in csharp

To modify an element in a Queue in C#, follow these steps:

  1. Dequeue the items from the Queue until you get to the one you want to modify. Store each dequeued item in a temporary Queue called tempQueue.
  2. Modify the item as needed.
  3. Enqueue the items from tempQueue back into the original Queue.

Here's the code:

main.cs
Queue<int> myQueue = new Queue<int>();

// add items to queue
myQueue.Enqueue(1);
myQueue.Enqueue(2);
myQueue.Enqueue(3);
myQueue.Enqueue(4);
myQueue.Enqueue(5);

// dequeue items until we find the one we want to modify
Queue<int> tempQueue = new Queue<int>();
bool found = false;
while (myQueue.Count > 0)
{
    int item = myQueue.Dequeue();
    if (item == 3)
    {
        // modify item
        item = 6;
        found = true;
    }
    tempQueue.Enqueue(item);
    
    if (found) break;
}

// enqueue items back into original queue
while (tempQueue.Count > 0)
{
    int item = tempQueue.Dequeue();
    myQueue.Enqueue(item);
}
633 chars
33 lines

In this example, we modify the item with a value of 3, changing it to 6. The resulting Queue would look like this: 1, 2, 6, 4, 5.

related categories

gistlibby LogSnag