获取队列c#中元素的索引

时间:2012-03-25 18:18:26

标签: c# asp.net .net queue

我在c#中有一个用户队列(电子邮件串)a,我想向用户发送他在此队列中的位置。

等等;

Queue q = new Queue(32);

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

    queue.IndexOf(email);

有什么想法吗?

感谢

8 个答案:

答案 0 :(得分:8)

对于此类操作,ListArray可能会更好,但您可以尝试这样做:

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

答案 1 :(得分:3)

您可以使用扩展方法,例如:

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;
}

答案 2 :(得分:1)

Queue不是使用IndexOf的正确类型,查找List

答案 3 :(得分:1)

不幸的是,你不能直接使用普通的旧.NET Queue对象。队列是为了“盲目的”先进先出逻辑而制作的,因此除了那之外你不能执行任何其他操作。

如果你真的需要实现一个队列,你可以在其中找到元素并检索它们的位置(一个非常有用的东西),试着将所有东西都包装在暴露以下方法的类中:

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

为了获得更好的性能(在indexOf O(n)时队列和出队O(1))你应该使用双链表

答案 4 :(得分:0)

如果你想让用户现在有多少元素是他的元素,只需在插入他的元素后返回当前队列.Count属性。每当你按下elemtn时,计数就会增加。如果弹出一个元素,则减少计数。

答案 5 :(得分:0)

使用Queue的{​​{1}}方法按队列的顺序获取数组,然后找到要搜索的对象。您很有可能不需要使用传统队列来执行您正在执行的任何任务。

类似的东西:

ToArray()

答案 6 :(得分:0)

西班牙宗教裁判所

受Monty Python素描的启发,您可以在整个犯罪嫌疑人队列中滑动,然后将每个项目出队并入队。并且在使用它时,您可以使用lambda函数将出队保持在枚举操作之内

//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()));
}

结果是可疑者列表,其中可疑者用箭头标记

SUSPECT_A
SUSPECT_B <---
SUSPECT_C

答案 7 :(得分:-1)

由于您正在为用户加号,他将始终是列表中的最后一个人,这意味着它将等同于queue.Count