Comparer Class

Overview

Good practice

  • When possible, use the generic version of IComparer<T> and Comparer<T>.

Examples

Compare Strings

// Returns 0 when equal, -1 when a < b and 1 when a > b
Console.WriteLine("Is a equal to b? {0}", Comparer.DefaultInvariant.Compare("a", "b"));

Reverse Sort

public class Program
{
    static void Main(string[] args)
    {
        ArrayList a = new ArrayList();
        a.AddRange(new string[] { "Hello", "World", "Aloha" });
        a.Sort();
        foreach (var s in a) { Console.WriteLine(s); }
        a.Sort(new ReverseSort());
        foreach (var s in a) { Console.WriteLine(s); }
    }
}
 
public class ReverseSort : IComparer
{
    public int Compare(object x, object y)
    {
        return y.ToString().CompareTo(x.ToString());
    }
}
 
learning/exam70-536/comparer.txt · Last modified: 2008/08/28 15:17 by david
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki