WPF中List的Add()与Insert()方法的区别

先来看看定义:

// Summary:
// Adds an object to the end of the System.Collections.Generic.List<T>.
//
// Parameters:
// item:
// The object to be added to the end of the System.Collections.Generic.List<T>.
// The value can be null for reference types.
View Code

public void Add(T item); 可以看出,Add方法只可接受一个参数,而且加入的元素会按加入的顺序进行排序,

如依次往List中Add(), 7 8 9 那么结果就是 {7, 8, 9}

再来看看Insert();

 1 //
 2 // Summary:
 3 // Inserts an element into the System.Collections.Generic.List<T> at the specified
 4 // index.
 5 //
 6 // Parameters:
 7 // index:
 8 // The zero-based index at which item should be inserted.
 9 //
10 // item:
11 // The object to insert. The value can be null for reference types.
12 //
13 // Exceptions:
14 // System.ArgumentOutOfRangeException:
15 // index is less than 0.-or-index is greater than System.Collections.Generic.List<T>.Count.
View Code

public void Insert(int index, T item); 该方法接受两个参数,第一个为下标,第二个为要添加的元素

需求: 要求往List中添加数据,而且后面加的数据始终要排在第一的位置,

 添加 5 6 7 8 9,通过Insert(0, number), 这里的0就代表第一个位置,那么结果为{9, 8, 7, 6, 5}

原文地址:https://www.cnblogs.com/tommy-huang/p/5279759.html