移除 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("Kevin");
      col.Add("Mary");
      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.RemoveAt(3);
      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
Kevin
Mary
Katie
Barry
Nathan
Mark
Count of elements (updated) = 8
Iterating through the collection... (updated)
Andy
Kevin
John
Mary
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("Three");
      col.Add("Four");
      col.Add("Five");
      col.Add("Six");
      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.RemoveAt(1);
      col.RemoveAt(2);
      col.RemoveAt(3);
      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 = 6
Iterating through the collection...
One
Two
Three
Four
Five
Six
Count of elements (updated) = 3
Iterating through the collection... (updated)
One
Three
Five

更新日期: 2019-12-05

121 人閱讀

開啟你的 職業生涯

完成課程認證

開始
廣告