Question

I need to write a comparer for a core class in C#. I have a SortedSet<Vector2> and in order to iterate through it I need a basic comparer. Nothing fancy needed as I just need to access each element in the collection in any order. But Vector2 (Microsoft.Xna.Framework.Graphics) is a compiled dll without a default comparer.

My SortedSet has a property Comparer but I cannot figure how to assign Comparer a Vector2 comparer.

Was it helpful?

Solution

You need to create your own class which implements IComparer<Vector2> and then constructor your SortedSet with it:

SortedSet<Vector2> sorted = new SortedSet<Vector2>(new MyCustomComparer());

Your comparer just needs to implement the single method Compare:

public class MyCustomComparer : IComparer<Vector2>
{
    public int Compare(Vector2 x, Vector2 y)
    {
        // Return appropriate value here, depending on the sort order you want
    }
}

OTHER TIPS

First, you need to create your custom comparer by implementing the IComparer<T> interface for Vector2.

You then have to instantiate your custom comparer and pass it to the constructor of SortedSet:

SortedSet(T) Constructor

Skeet has given one good solution. If you use .NET version 4.5, you can also use a lambda expression, like this:

new SortedSet<Vector2>(Comparer<Vector2>.Create(
    (v1, v2) => v1.X.CompareTo(v2.X)
    )

In the above example I just supposed the Vector2 values should simply be compared by X coordinate (and vectors with same X will be considered equally "great" by my comparer).

For another example comparing by length:

new SortedSet<Vector2>(Comparer<Vector2>.Create(
    (v1, v2) => (v1.X * v1.X + v1.Y * v1.Y).CompareTo(v2.X * v2.X + v2.Y * v2.Y)
    )

Of course, if the logic determining if v1 is less, equal, or greater than v2 is complex, it's better to have a usual method for it, but for simple things, lambdas are great because you don't need to write a new class or anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top