C#のコレクションからオブジェクトの最初の出現を削除します
コレクションからオブジェクトの最初の出現を削除するためのコードは次のとおりです-
例
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("Nathan");
col.Add("Nathan");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("Count of elements = "+ col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
col.Remove("Nathan");
Console.WriteLine("Count of elements (updated) = "+ col.Count);
Console.WriteLine("Iterating through the collection... (updated)");
enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
} 出力
これにより、次の出力が生成されます-
Count of elements = 9 Iterating through the collection... Andy Kevin John Nathan Nathan Katie Barry Nathan Mark Count of elements (updated) = 8 Iterating through the collection... (updated) Andy Kevin John Nathan Katie Barry Nathan Mark
例
別の例を見てみましょう-
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Two");
col.Add("Four");
col.Add("Five");
col.Add("Two");
col.Add("Six");
col.Add("Seven");
Console.WriteLine("Count of elements = "+ col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
col.Remove("Two");
Console.WriteLine("Count of elements = "+ col.Count);
Console.WriteLine("Iterating through the collection... (updated)");
enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
} 出力
これにより、次の出力が生成されます-
Count of elements = 8 Iterating through the collection... One Two Two Four Five Two Six Seven Count of elements = 7 Iterating through the collection... (updated) One Two Four Five Two Six Seven
-
C#のStringDictionaryからすべてのエントリを削除する
StringDictionaryからすべてのエントリを削除するには、コードは次のとおりです- 例 using System; using System.Collections; using System.Collections.Specialized; public class Demo { public static void Main(){ StringDictionary strDict1 = new StringDictionary(); strDict1.Add("
-
C#のコレクションから要素を取得する
リストコレクションの例を見てみましょう。 要素を設定しました- List<int> list = new List<int>(); list.Add(20); list.Add(40); list.Add(60); list.Add(80); ここで、リストから最初の要素を取得する必要があるとします。そのためには、このようにインデックスを設定します- int a = list[0]; 以下は、リストコレクションから要素を取得する方法を示す例です- 例 using System; using System.Collections.Generic; class De