Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
List 的 Add 和 Insert 操作有什么区别?
List<Tuple<int,string>> samplelinq = new List<Tuple<int, string>>();
在这里,我想列出一个元组。我应该使用添加还是插入。
幸运的是,文档解释了Add和之间的区别:Insert
Add
Insert
添加
将对象添加到列表的末尾。
签名:
public void Add (T item);
插入
将元素插入到 List 中指定索引处。
public void Insert (int index, T item);
概括
因此,关于哪个更好的问题的答案完全取决于您要达到的目标。如果您只是想将一个项目添加到列表的末尾,请使用Add.
Add 将始终插入到数组的末尾,而 Insert 允许您选择索引。当我积累东西时,我通常更喜欢添加。但是,如果结构的顺序很重要并且需要改变/更改(例如,如果新元素需要位于位置 4),那么 Insert 就是要走的路。