Make Types Sortable
Scenario/Problem: |
Objects of your type will be sorted in a collection or otherwise compared to each other. |
Solution: |
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 |
Ø |
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.
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 = Ø; } ... public int CompareTo(Vertex3d other) { if (_id < other._id) return -1; if (_id == other._id) return Ø; return 1; /* We could also just do this: * return _id.CompareTo(other._id); * */ } }