Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Make Types Sortable (http://www.go4expert.com/forums/make-types-sortable-t21338/)

arunlalds 13Mar2010 15:10

Make Types Sortable
 
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);
* */
}
}



All times are GMT +5.5. The time now is 10:24.