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

  • 相关阅读:
    1035: 相同生日
    1034: 7, 还是7
    1033: 青蛙的约会
    1032: 蛇行矩阵
    1031: 最少钱币数
    1030: 到底买不买
    1029: 挖掘机技术哪家强
    scikit-learn 和pandas 基于windows单机机器学习环境的搭建
    用scikit-learn和pandas学习线性回归
    SimRank协同过滤推荐算法
  • 原文地址:https://www.cnblogs.com/taoxu0903/p/1798095.html
Copyright © 2020-2023  润新知