Skip to main content

Posts

Showing posts from May, 2010

Which Dictionary object should you use?

Hashtable SortedList String Dictionary List Dictionary Hybrid Dictionary NameValue Collection Retrieved by name Yes Yes Yes Yes Yes Yes Retrieved by Index Yes Yes Yes Yes Yes Yes Sorted by default No Yes No Key type Object String String (Strongly typed) Object Object String/ Integer Value type Object Object String Object Object Object Performance Optimised for fewer than 10 items Uses List Dictionary for small no of item. Changes to Hashtable as list grows Allows multiple value for a key

How to make a Custom Sort Function

You can create your won custome IComparer implementation to control sort order. While IComparable.CompareTo method controls the default sort order for a class, IComparer.Compare can be used to provide custom sort order. For e.g. following class which implements IComapere, provides custom reverse sort public class reverseSort : IComparer { int IComparer.Compare(Object y, Object x) { return ((new CaseInsensitiveComparer()).Compare(x, y)); } } //test class ArrayList al = new ArrayList(); al.AddRange(new String[] {"This", "is", "a", "Amazing", "world", "of", "Collections" }); //default sort order ascending al.Sort(); foreach (object o in al) { Console.WriteLine(o.ToString()); } //custom sort order al.Sort(new reverseSort()); foreach (object o in al) { Console.WriteLine(o.ToString()); }