C# 将对象添加到泛型 List<T> 的开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/705969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding object to the beginning of generic List<T>
提问by kaivalya
Add method Adds an object to the end of the List<T>
Add 方法将对象添加到对象的末尾 List<T>
What would be a quick and efficient way of adding object to the beginning of a list?
将对象添加到列表开头的快速有效方法是什么?
采纳答案by Marc Gravell
Well, list.Insert(0, obj)
- but that has to move everything. If you need to be able to insert at the start efficiently, consider a Stack<T>
or a LinkedList<T>
嗯,list.Insert(0, obj)
- 但这必须移动一切。如果您需要能够有效地在开始时插入,请考虑 aStack<T>
或 aLinkedList<T>
回答by Martin Brown
List<T> l = new List<T>();
l.Insert(0, item);
回答by Guffa
You can insert items at the beginning of the list, but that is not very efficient, especially if there are many items in the list.
您可以在列表的开头插入项目,但这不是很有效,尤其是当列表中有很多项目时。
To avoid that you can redefine what you use as beginning and end of the list, so that the last element is the beginning of the list. Then you just use Add to put an element at the beginning of the list, which is much more efficient than inserting items at position zero.
为避免这种情况,您可以重新定义用作列表开头和结尾的内容,以便最后一个元素是列表的开头。然后你只需使用 Add 将一个元素放在列表的开头,这比在位置零插入项目更有效。