An IComparer

In .Net you can very easily create a special class to handle comparing of (custom) objects. All you have to do is implement the IComparer or IComparer interface and implement it’s one simple function: Compare.

So write a class that implements it:

public class MyComparer : IComparer<MyObj>
{
public int Compare(MyObj x, MyObj y) {
// If, for example you're working with an int:
return x.IntProperty.CompareTo(y.IntProperty);

// If, perhaps, it is a string:
return string.CompareTo(x.StringProperty, y.StringProperty)
}
}

The value you return must be negative if x is less then y, 0 if x is equal to y or greater then 0 if x is greater then y.

This can of course be used with things like MyCollection.Sort(new MyComparer()), really handy if you have strange objects.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s