Collection < T > .Insert(Int32,T)方法用于将元素插入到指定索引处的Collection
句法:
public void Insert (int index, T item);
参数:
index : The zero-based index at which item should be inserted.
item : The object to insert. The value can be null for reference types.
异常:如果index小于零或index大于Count,则此方法将提供ArgumentOutOfRangeException。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to insert an element into
// the Collection at the specified index
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of strings
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add("A");
myColl.Add("B");
myColl.Add("C");
myColl.Add("D");
myColl.Add("E");
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
// Inserting an element into the
// Collection at the specified index
myColl.Insert(2, "GFG");
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(string str in myColl)
{
Console.WriteLine(str);
}
}
}
输出:
Count : 5
A
B
C
D
E
Count : 6
A
B
GFG
C
D
E
范例2:
// C# code to insert an element into
// the Collection at the specified index
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
// Driver code
public static void Main()
{
// Creating a collection of ints
Collection myColl = new Collection();
// Adding elements in Collection myColl
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
// Inserting an element into the
// Collection at the specified index
// This should raise "ArgumentOutOfRangeException"
// as index is less than 0
myColl.Insert(-1, 8);
// Displaying the number of elements in myColl
Console.WriteLine("Count : " + myColl.Count);
// Displaying the elements in myColl
foreach(int i in myColl)
{
Console.WriteLine(i);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index must be within the bounds of the List.
Parameter name: index
笔记:
- Collection < T >接受null作为引用类型的有效值,并允许重复的元素。
- 如果index等于Count,则将项目添加到Collection < T >的末尾。
- 此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.objectmodel.collection-1.insert?view=netframework-4.7.2