public class Foobar : IComparable { private int a; private string b; public Foobar() : this(0, "") { } public Foobar(int a, string b) { this.a = a; this.b = b; } public int A { get { return a; } set { a = value; } } public string B { get { return b; } set { b = value; } } public int CompareTo(object o) { return (a - ((Foobar)o).A); } public override string ToString() { return ("(" + a + "," + b + ")"); } }
public class FoobarAComparer : IComparer { int IComparer.Compare(Object o1, Object o2) { return (((Foobar)o1).A - ((Foobar)o2).A); } }
public class FoobarRevAComparer : IComparer { int IComparer.Compare(Object o1, Object o2) { return -(((Foobar)o1).A - ((Foobar)o2).A); } }
public class FoobarBComparer : IComparer { int IComparer.Compare(Object o1, Object o2) { return (((Foobar)o1).B.CompareTo(((Foobar)o2).B)); } }
public class FoobarRevBComparer : IComparer { int IComparer.Compare(Object o1, Object o2) { return -(((Foobar)o1).B.CompareTo(((Foobar)o2).B)); } }
class ManySort { private static void print(string descr, ArrayList list) { Console.Write(descr + ": ["); foreach(object o in list) { Console.Write(o); } Console.WriteLine("]"); } public static void Main(string[] args) { ArrayList list = new ArrayList(); list.Add(new Foobar(5, "AAAAA")); list.Add(new Foobar(4, "BBBB")); list.Add(new Foobar(3, "CCC")); list.Add(new Foobar(2, "DD")); list.Add(new Foobar(1, "E")); print("Original", list); list.Sort(); print("After natural sort (= sort on A)", list); list.Sort(new FoobarRevAComparer()); print("After reverse sort on A", list); list.Sort(new FoobarAComparer()); print("After sort on A", list); list.Sort(new FoobarBComparer()); print("After sort on B", list); list.Sort(new FoobarRevBComparer()); print("After reverse sort on B",list); } }
Implementation af klasse der sortere en række strenge på det tal der står på plads 2 i strengen: eksempel: A2 B1
bliver sorteret som B1 A2
public class ComparerData : IComparer { public int Compare( object a, object b ) { if( a != null && b != null && a is string && b is string ) { int aInt = int.Parse( ((string)a).Substring( 1,1 ) ); int bInt = int.Parse( ((string)b).Substring( 1,1 ) );
return aInt.CompareTo( bInt ); }
return -1; } }
Test af ICompare:
ArrayList data = new ArrayList(); data.Add( "a2" ); data.Add( "b1" );
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.