Get the index of an item inside a C # queue

I have a user queue (a string of letters) a in C #, and I want to send the user his location in this queue.

sort of:

Queue q = new Queue(32); q.Enqueue(Session["email"].ToString()); queue.IndexOf(email); 

Any ideas?

thanks

+6
source share
7 answers

It might be better for List or Array , but you could try the following:

 queue.ToArray().ToList().IndexOf(email); 
+8
source

You can use the extension method, for example:

 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; } 
+3
source

Queue is not an appropriate type to use IndexOf, find List

+1
source

Unfortunately, you cannot directly use the plain old .NET Queue object. The queue is executed for the blind first-in-first-end logic, so you cannot execute anything but this.

If you really need to implement a queue in which you can find the elements and get their position (a very useful thing), try wrapping everything in a class that provides 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++; } } } 

To improve performance (queue and dequeue O (1), while indexOf O (n)), you should use a double-linked list

+1
source

if you want the user to now show how many elements his element is executing, simply return the current .Count property by inserting his elements. Whenever you click on an item, the score increases. If an item pops up, the counter decreases.

0
source

Use the Queue ToArray() method to get the array in queue order, then find the object you are looking for. There is a good chance that you do not need to use the traditional queue for any task that you perform.

Sort of:

 Queue q = new Queue(); q.Enqueue("apple"); q.Enqueue("banana"); q.Enqueue("orange"); // get banana index: return Array.IndexOf(q.ToArray(), "banana"); 
0
source

As you enter the user's queue, he will always be the last person on the list, which means that he will be equivalent to queue.Count .

-1
source

Source: https://habr.com/ru/post/911612/


All Articles