简体   繁体   English

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

[英]How to always keep n elements of a collection?

What is the best way to keep n elements of a collection in c# ? 在c#中保存集合的n个元素的最佳方法是什么?

Remove old elements when adding a new one. 添加新元素时删除旧元素。

保留集合的n个元素

This is what I did: 这就是我做的:

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

Is there any other way to do it? 还有其他办法吗?

What you want is a circular buffer . 你想要的是一个循环缓冲区 There are many implementations out there. 那里有很多实现。 Here is one . 这是一个

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. 及时,因为插入是O(1)并且在空间中,因为新元素会覆盖最旧的就地。

Your first attempt is not efficient because RemoveAt(0) is O(n) because the elements have to shift. 你的第一次尝试效率不高,因为RemoveAt(0)O(n)因为元素必须移位。

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. 第三次尝试是最好的,因为.NET队列强制作为循环缓冲区,但是有一些处理调整大小的开销。 Since you don't care about resizing, a true circular buffer with a fixed size would be a bit more efficient. 由于您不关心调整大小,因此具有固定大小的真正循环缓冲区会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM