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?

Recommended Answers

All 3 Replies

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

Try this for your Compare method.

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

Thank you very much Mr. Crane.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.