在 C# 中將元素插入指定索引處的集合
要插入一個元素到集合中指定索引處,程式碼如下 −
示例
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach(string str in col){
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
Console.WriteLine("Element at index 4 = " + col[4]);
col.Insert(5, "Alienware");
Console.WriteLine("Elements in Collection...UPDATED");
foreach(string str in col){
Console.WriteLine(str);
}
}
}輸出
這將產生以下輸出 −
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 4 = Tablet Elements in Collection...UPDATED Laptop Desktop Notebook Ultrabook Tablet Alienware Headphone Speaker
示例
我們現在來看另一個示例 −
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
Console.WriteLine("Elements in Collection...");
foreach(string str in col){
Console.WriteLine(str);
}
col.Insert(3, "Jacob");
Console.WriteLine("Elements in Collection...UPDATED");
foreach(string str in col){
Console.WriteLine(str);
}
}
}輸出
這將產生以下輸出 −
Elements in Collection... Andy Kevin John Kevin Mary Katie Barry Nathan Elements in Collection...UPDATED Andy Kevin John Jacob Kevin Mary Katie Barry Nathan
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP