0

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?

2
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by DaveTran
0

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 by nick.crane: n/a

1

Try this for your Compare method.

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

Edited by nick.crane: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.