删除 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

更新于: 2019 年 12 月 6 日

74 次浏览

开启您的职业生涯

完成课程,获取认证

开始学习
广告