.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. 

 

 

转载于:https://www.cnblogs.com/taoxu0903/archive/2010/08/12/1798095.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值