从C#中的Collection中删除第一次出现的对象
要从Collection中删除对象的第一次出现,代码如下-
示例
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
热门推荐
10 朋友结婚致辞祝福语简短
11 春节拜年祝福语儿童简短
12 2026新年祝福语简短语
13 老师新婚快乐祝福语简短
14 祝贺新店开业祝福语简短
15 年后祝福语简短走心
16 双十一祝福语大全简短
17 庆祝国家的祝福语简短
18 感动妈妈的祝福语简短