Monday, 17 December 2012

c sharp programming

IComparer and Comparer
Comparers are used to switch in custom ordering logic for sorted dictionaries and
collections.
Note that a comparer is useless to the unsorted dictionaries such as Dictionary and
Hashtable—these  require  an  IEqualityComparer  to  get  hash  codes.  Similarly,  an
equality comparer is useless for sorted dictionaries and collections.
Here are the IComparer interface definitions:
public interface IComparer
{
  int Compare(object x, object y);
}
public interface IComparer <in T>
{
  int Compare(T x, T y);
}
As with equality comparers,  there’s an abstract class you can  subtype  instead of
implementing the interfaces:
public abstract class Comparer<T> : IComparer, IComparer<T>
{
   public static Comparer<T> Default { get; }
   public abstract int Compare (T x, T y);       // Implemented by you
   int IComparer.Compare (object x, object y);   // Implemented for you
}
The following example illustrates a class that describes a wish, and a comparer that
sorts wishes by priority:

class Wish
{
  public string Name;
  public int Priority;
  public Wish (string name, int priority)
  {
    Name = name;
    Priority = priority;
  }
}
class PriorityComparer : Comparer <Wish>
{
  public override int Compare (Wish x, Wish y)
  {
    if (object.Equals (x, y)) return 0;          // Fail-safe check
    return x.Priority.CompareTo (y.Priority);
  }
}

The object.Equals check ensures that we can never contradict the Equals method.
Calling the static object.Equals method in this case is better than calling x.Equals
because it still works if x is null!
Here’s how our PriorityComparer is used to sort a List:
var wishList = new List<Wish>();
wishList.Add (new Wish ("Peace", 2));
wishList.Add (new Wish ("Wealth", 3));
wishList.Add (new Wish ("Love", 2));
wishList.Add (new Wish ("3 more wishes", 1));
wishList.Sort (new PriorityComparer());
foreach (Wish w in wishList) Console.Write (w.Name + " | ");
// OUTPUT: 3 more wishes | Love | Peace | Wealth |
In the next example, SurnameComparer allows you to sort surname strings in an order
suitable for a phonebook listing:
class SurnameComparer : Comparer <string>
{
  string Normalize (string s)
  {
    s = s.Trim().ToUpper();
    if (s.StartsWith ("MC")) s = "MAC" + s.Substring (2);
    return s;
  }

  public override int Compare (string x, string y)
  {
    return Normalize (x).CompareTo (Normalize (y));
  }
}
Here’s SurnameComparer in use in a sorted dictionary:
var dic = new SortedDictionary<string,string> (new SurnameComparer());
dic.Add ("MacPhail", "second!");
dic.Add ("MacWilliam", "third!");
dic.Add ("McDonald", "first!");
foreach (string s in dic.Values)
  Console.Write (s + " ");              // first! second! third!

No comments:

Post a Comment