.Net Collection Comparer

If you know some C++ STL, you should know that we can pass in a function object when constructing a STL map, set, etc to let the container use that function to do comparison for its elements. Now what about such functionality in .Net?

For sortedDictionary like containers which can accept  System.IComparable as argument for constructing:

Two ways to do such work:

1. Let the container element object to implement IComparable interface, which will let the container like Dictionary, HashSet, etc to make use of it.

2. Implement a separate class which implements Comparer<T> class, and then pass a created object of it as argument to construct your Dictionary, Hashset, etc.

 

The difference between deriving from the Comparer<T> class and implementing the System.IComparable interface is as follows:

  • To specify how two objects should be compared by default, implement the System.IComparable interface in your class. This ensures that sort operations will use the default comparison code that you provided.

  • To define a comparer to use instead of the default comparer, derive from the Comparer<T> class. You can then use this comparer in sort operations that take a comparer as a parameter.

For Dictionary like container which can only accept IEqualityComparer<T> in its constructor, yes, we need to create a class that implements IEqualityComparer<T> OR inherit from EqualityComparer<T> and pass its object when constructing the container. Then when calling Dictionary.contains(), etc method, such comparer will be used.

MSDN comment:

We recommend that you derive from the EqualityComparer<T> class instead of implementing the IEqualityComparer<T> interface, because the EqualityComparer<T> class tests for equality using the IEquatable<T>.Equals method instead of the Object.Equals method. This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey, TValue> class and other generic collections. 

 

 

posted @ 2010-08-12 14:01  能巴  阅读(291)  评论(0编辑  收藏  举报