从列表中删除旧值
我有一个列表,我希望能够存储 20 个值。删除旧值的好方法是什么?一个更好的例子是,想象一下更改历史记录,我不希望能够存储 20 个最新更改,而较旧的更改则消失。
C# 中是否有特殊的功能可以让我这样做,或者我必须自己制作或使用“删除”功能。
EDIT1:好吧,存储 4000 - 10000 个值怎么样,突然间链表看起来很有吸引力。
编辑2:循环列表很好,但是,我不想循环我的旧值。
EDIT3:对于我的问题,随机访问不太重要,但顺序访问很重要。
I have a list that I want to be able to store 20 values. What would be a good approach to deleting older values. A better example would be, imagine a change history and I wan't to be able to store 20 latest changes, while older ones go away.
Is there a special thing in C# that will let me do that or do I have to either make my own or use the Remove function.
EDIT1: Alright, how about storing 4000 - 10000 values, suddenly a linked-list looks attractive.
EDIT2: Circular list is good BUT, I don't want to be able to loop my older values.
EDIT3: For my problem, random access isn't too important, but sequential access is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用队列。每次入队时检查 size == 20 是否。如果是,则出列/弹出一个元素
use a Queue. each time you enqueue into the queue check if size == 20. If so, dequeue/pop one element
听起来你正在描述一个环形缓冲区。 如何编写高效的循环缓冲区Java 或 C# 可能会有所帮助。
Sounds like you're describing a ring buffer. How would you code an efficient Circular Buffer in Java or C# might be helpful.
您可以创建自己的列表类:
You can make your own list class:
没有内置的集合可以处理这个问题,但您可以轻松制作一个:
但请注意,当前仅处理使用
Add
方法添加项目时的限制,而不是其他方法(如)添加范围
和插入
。此外,正如 SLask 指出的那样,List
类并不是专门用于继承的(尽管它没有标记为final
),因此更健壮的实现将封装列表而不是继承它。另请注意,删除大型列表中的第一项效率很低,但只要项目数少至 20 个,就没有问题。如果您需要更大的集合,LinkedList 可以更好地处理这个问题。
There is no built in collection that handles that, but you could easily make one:
Note though that this currently only handles the limit when items are added using the
Add
method, and not other methods likeAddRange
andInsert
. Also, as SLask pointed out, theList<T>
class isn't specifically intended to be inherited (although it's not marked asfinal
), so a more robust implementation would encapsulate the list instead of inheriting from it.Note also that it's inefficient to remove the first item in a large list, but with as few items as 20, there is no problem. A LinkedList would handle that better if you need a much larger collection.
好吧,我终于有机会自己思考这个问题,并找到了一个很好的折衷方案,而不需要花费太多的努力。为什么不直接使用链表呢?
我想我没有提到随机访问并不是太重要......
Alright I finally got a chance to think about this problem myself and found a good compromise without going through too much effort. Why not just use a linked list.
I guess I failed to mention that random access wasn't too important...