I would like to sort an array of objects by their distance. The problem is that the distance value is a floating point and IComparer only will accept an integer as a return value.

class SortDistanceAscending : IComparer<ObjectDistance>
    {
        static IComparer<ObjectDistance> comparer = new SortDistanceAscending();

        public int Compare(ObjectDistance a, ObjectDistance b)
        {
            return a.Distance - b.Distance;
        }

        public static IComparer<ObjectDistance> Comparer
        {
            get { return comparer; }
        }
    }

How can I keep the accuracy of comparing two floats in this case?

The result from the IComparer.Compare is the result of the comparison, not the difference between the values tested.

Less than zero (usually -1)       means    x is less than y.  
Zero                              means    x equals y.
Greater than zero (usually +1)    means    x is greater than y.

See IComparer.Compare Method

Edited 6 Years Ago by nick.crane: n/a

Try this for your Compare method.

public int Compare(ObjectDistance a, ObjectDistance b)
        {
            return Comparer<float>.Default.Compare(a.Distance, b.Distance);
        }

Edited 6 Years Ago by nick.crane: n/a

This question has already been answered. Start a new discussion instead.