zoukankan      html  css  js  c++  java
  • .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. 

  • 相关阅读:
    Mysql 怎么限制 IP 访问?
    LA2965 n个数中选出最多个数异或和为0
    UVALive 2678 大于s的最短子序列和
    UVA 1193 区间相关(greedy)
    UVA 11992 线段树
    UVA 1400 线段树
    NBUT 1120 线段树
    最大连续区间和的算法总结(转)
    hiho 1015 KMP
    hiho#1128 : 二分·二分查找
  • 原文地址:https://www.cnblogs.com/taoxu0903/p/1798095.html
Copyright © 2011-2022 走看看