// 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; using System.Linq; namespace Comp { public class A { public int IV { get; set; } public string SV { get; set; } public override string ToString() { return string.Format("[{0},{1}]", IV, SV); } } public class B : IComparable { public int IV { get; set; } public string SV { get; set; } public int CompareTo(B o) { return IV.CompareTo(o.IV); } public override string ToString() { return string.Format("[{0},{1}]", IV, SV); } } public class C : IComparable { public int IV { get; set; } public string SV { get; set; } public int CompareTo(C o) { return SV.CompareTo(o.SV); } public override string ToString() { return string.Format("[{0},{1}]", IV, SV); } } public class Program { public static void Main(string[] args) { List lsta = new List { new A { IV = 111, SV = "A" }, new A { IV = 22, SV = "BB" }, new A { IV = 3, SV = "CCC" } }; try { lsta.Sort(); } catch(InvalidOperationException) { Console.WriteLine("A does not implement IComparable"); } List lstb = new List { new B { IV = 111, SV = "A" }, new B { IV = 22, SV = "BB" }, new B { IV = 3, SV = "CCC" } }; lstb.Sort(); Console.WriteLine(string.Join(":", lstb)); List lstc = new List { new C { IV = 111, SV = "A" }, new C { IV = 22, SV = "BB" }, new C { IV = 3, SV = "CCC" } }; lstc.Sort(); Console.WriteLine(string.Join(":", lstc)); } } }