1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Make Types Sortable

Discussion in 'C#' started by arunlalds, Mar 13, 2010.

  1. arunlalds

    arunlalds Banned

    Joined:
    Mar 12, 2010
    Messages:
    43
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    student
    Location:
    India
    Because you often don’t know how your type will be used, making the
    objects sortable is highly recommended whenever possible.
    In the Vector3d class example, in order to make the objects comparable, we’ll add an
    _id field and implement the IComparable<Vertex3d> interface.
    The _id field will be what determines the order (it doesn’t make much sense to sort on
    coordinates, generally).
    The sorting function is simple. It takes an object of Vertex3d and returns one of three
    values:
    < 0 this is less than other
    0 this is same as other
    > 0 this is greater than other
    Within the CompareTo function, you can do anything you want to arrive at those
    values. In our case, we can do the comparison ourself or just call the same function on
    the _id field.
    Code:
    struct Vertex3d : IFormattable, IEquatable<Vertex3d>,
    IComparable<Vertex3d>
    {
    private int _id;
    public int Id
    {
    get
    {
    return _id;
    }
    set
    {
    _id = value;
    }
    }
    public Vertex3d(double x, double y, double z)
    {
    _x = x;
    _y = y;
    _z = z;
    _id = 0;
    }
    ...
    public int CompareTo(Vertex3d other)
    {
    if (_id < other._id)
    return -1;
    if (_id == other._id)
    return 0;
    return 1;
    /* We could also just do this:
    * return _id.CompareTo(other._id);
    * */
    }
    }
    
     

Share This Page