📌  相关文章
📜  C#|将元素插入集合<T>在指定索引处

📅  最后修改于: 2021-05-29 20:41:45             🧑  作者: Mango

Collection < T > .Insert(Int32,T)方法用于将元素插入到指定索引处的Collection 中。

句法:

public void Insert (int index, T item);

参数:

异常:如果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);
        }
    }
}

运行时错误:

笔记:

  • 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