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
-
HashSetと指定されたコレクションがC#で共通の要素を共有しているかどうかを確認します
HashSetと指定されたコレクションが共通の要素を共有しているかどうかを確認するには、C#コードは次のとおりです- 例 using System; using System.Collections.Generic; public class Demo { public static void Main(){ HashSet<int> set1 = new HashSet<int>(); set1.Add(25); se
-
インデックスを使用してアイテムをC#リストに挿入するにはどうすればよいですか?
まず、リストを設定します- List<int> list = new List<int>(); list.Add(456); list.Add(321); list.Add(123); list.Add(877); list.Add(588); list.Add(459); ここで、インデックス5にアイテムを追加するには、次のように言います。そのためには、Insert()メソッドを使用します- list.Insert(5, 999); 完全な例を見てみましょう- 例 using System; using System.Collections.Generic; n