如何始终保持集合的n个元素?

A. *_*rel 3 c# collections

将集合的n个元素保留在c#中的最佳方法是什么?

添加新元素时,请删除旧元素。

保留集合的n个元素

这是我所做的:

List<int> listOf5Elements = new List<int>();
for(var i = 0; i<200; i++)
{
    listOf5Elements.Add(i);
    if (listOf5Elements.Count() == 6)
        listOf5Elements.RemoveAt(0);
}

LinkedList<int> linkedOf5elements = new LinkedList<int>();
for (var i = 0; i < 200; i++)
{
    linkedOf5elements.AddLast(i);
    if (linkedOf5elements.Count() == 6)
        linkedOf5elements.RemoveFirst();
}

Queue<int> queueOf5Elements = new Queue<int>();
for (var i = 0; i < 200; i++)
{
    queueOf5Elements.Enqueue(i);
    if (queueOf5Elements.Count() == 6)
        queueOf5Elements.Dequeue();
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?

Kit*_*Kit 5

您想要的是一个循环缓冲区。有很多实现。这是一个

It's efficient in both time and space; in time because an insert is O(1) and in space because the new element overwrites the oldest in-place.

Your first attempt is not efficient because RemoveAt(0) is O(n) because the elements have to shift.

The second isn't too bad, but has some overhead in allocating the new slot, and deleting the old one.

The third attempt is the best because the .NET queue is impemented as a circular buffer, but there's some overhead dealing with resizing. Since you don't care about resizing, a true circular buffer with a fixed size would be a bit more efficient.