Get the index of an element inside queue c#

I have a queue of users(string of emails) a in c# and I want to send the user his location in this queue.

something like ;

Queue q = new Queue(32);

q.Enqueue(Session["email"].ToString());

    queue.IndexOf(email);

Any ideas?

thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Maybe a List or an Array would be better for such actions but you could try this:

queue.ToArray().ToList().IndexOf(email);

Method 2

You can use extension method, something like:

public static int IndexOf<T>(this IEnumerable<T> collection, T searchItem)
{
    int index = 0;

    foreach (var item in collection)
    {
        if (EqualityComparer<T>.Default.Equals(item, searchItem))
        {
            return index;
        }

        index++;
    }

    return -1;
}

Method 3

Queue is not the proper type to use IndexOf, look for List

Method 4

Unfortunately, you cannot straightly use the plain old .NET Queue object. Queue is made for “blind” first-in-first-out logic, so that you cannot perform anything else but that.

If you really need to implement a queue in which you can find elements and retrieve their position (a very useful thing) try to wrap everything in a class that exposes the following methods:

public class CustomQueue<T> {
    private LinkedList<T> fifoList = new LinkedList<T>();

    public Enqueue(T newItem) {
        //add newItem at the head of fifoList
    }

    public T Dequeue() {
        //return and remove the item that is located at the tail of the queue
    }

    public int indexOf(T searchFor) {
        int ret = 0;
        for (T item: fifoList) {
            if (item.equals(searchFor)) return ret;
            ret++;
        }
    }
}

For better performance (queue and dequeue O(1) while indexOf O(n)) you should use a double-linked list

Method 5

if you want to let the user now how many elements are behins his element, simply return the current queue .Count property, after inserting his elements. Whenever you push an elemtn, the count is increased. If an element is popped, the count is decreased.

Method 6

Use the Queue‘s ToArray() method to get an array in the order of the queue, then find the object you are searching for. There’s a good chance you don’t need to use a traditional queue for whatever task you are performing though.

Something like:

Queue q = new Queue();
q.Enqueue("apple");
q.Enqueue("banana");
q.Enqueue("orange");

// get banana index:
return Array.IndexOf(q.ToArray(), "banana");

Method 7

Spanish Inquisition

Inspired by Monty Python sketch you could swipe through the entire queue of suspects and dequeue and enqueue each item once. And while you are at it you can use a lambda function to kind of keep the dequeuing within the enquing operation

//The queue
var inquisition = new Queue<string>();
    
//Suspects
inquisition.Enqueue("SUSPECT_A");
inquisition.Enqueue("SUSPECT_B");
inquisition.Enqueue("SUSPECT_C");

//Interrogation lambda function noting particular suspect before returned
Func<string, string> interrogate = (suspect) => {
    Console.WriteLine(suspect + (suspect.Equals("SUSPECT_B") ? " <---" : ""));
    return suspect;
};
    
//Processing each suspect in the list
for(var i=0;i<inquisition.Count;i++){
    inquisition.Enqueue(interrogate(inquisition.Dequeue()));
}

The result is a list of suspects where dubious ones are marked with an arrow

SUSPECT_A
SUSPECT_B <---
SUSPECT_C

Method 8

I know this is an older thread, but was relevant to me. In my case the Queue object was perfect for the job it was intended to do, but I had a separate process that reports a status of the objects in queue and I wanted to report the queue position for each queued item. Here was my solution and this illustrates how converting a queue to a list can be helpful. Once converted to a list, you can perform Linq queries on it as well. In this case, I needed to find an export object by its status property:

Dim ExpQueueList As List(Of Export) = ExportQueue.ToList()

For Idx As Integer = 0 To ExportStatuses.Count - 1
    Dim Status As ExportStatus = ExportStatuses(Idx)

    'Find the export that this status belongs to in the queued export list
    Dim ExpObj As Object = (From E As Export In ExpQueueList Where E.Status Is Status Select E).FirstOrDefault()

    'If the export was found in the queue list, set the status text to indicate the position in the queue
    If ExpObj IsNot Nothing Then
        Status.StatusText = "In Queue to run - Queue Position: " & ExpQueueList.IndexOf(ExpObj)
    End If

    ExpObj = Nothing
    Status = Nothing
Next

Method 9

Since you’re enqueing the user, he will always be the last person in the list, which means it will be equivalent to queue.Count.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x