// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; namespace E { public class Foobar { public Foobar() : this("") { } public Foobar(string v) { V = v; } public string V { get; set; } public override string ToString() { return "[Foobar:" + V + "]"; } public override bool Equals(object obj) { Foobar fbobj = (Foobar)obj; return V.Equals(fbobj.V); } public override int GetHashCode() { return V.GetHashCode(); } } public class Program { public static void Main(string[] args) { List lst = new List(); lst.Add(new Foobar("A")); lst.Add(new Foobar("A")); lst.Add(new Foobar("A")); lst.Add(new Foobar("B")); lst.Add(new Foobar("B")); lst.Add(new Foobar("B")); foreach(Foobar fb in lst) { Console.WriteLine(fb); } //********** Console.WriteLine("Remove in forward loop"); List clon1 = new List(lst); for(int i = 0; i < clon1.Count; i++) { if(clon1[i].V == "A") { clon1.RemoveAt(i); } } foreach(Foobar fb in clon1) { Console.WriteLine(fb); } //********** Console.WriteLine("Remove in backward loop"); List clon2 = new List(lst); for(int i = clon2.Count - 1; i >= 0; i--) { if(clon2[i].V == "A") { clon2.RemoveAt(i); } } foreach(Foobar fb in clon2) { Console.WriteLine(fb); } //********** Console.WriteLine("Utilize Equals method with Remove"); List clon3 = new List(lst); while(clon3.Remove(new Foobar("A"))); foreach(Foobar fb in clon3) { Console.WriteLine(fb); } //********** Console.WriteLine("The .NET 2.0 way with delegate"); List clon4 = new List(lst); clon4.RemoveAll(delegate(Foobar fb) { return fb.V == "A"; }); foreach(Foobar fb in clon4) { Console.WriteLine(fb); } //********** Console.WriteLine("The .NET 3.5 way with Lambda"); List clon5 = new List(lst); clon5.RemoveAll((Foobar fb) => fb.V == "A"); foreach(Foobar fb in clon5) { Console.WriteLine(fb); } } } }