-1

Scenario

I have a custom class (called FeedData) that would collected in a HashSet<FeedData>

internal struct FeedData
{
    internal string ID;
    internal Vector2d Location;
}

I now have a custom IComparer that would help sort the HashSet<FeedData> from nearest to the farthest location to the user's location. The comparision happens with FeedData.Location

internal sealed class DistanceComparer : IComparer<FeedData>
{

    private CheapRuler cheapRuler;
    private Vector2d userLocation;

    //Constructor
    internal DistanceComparer(Vector2d _currentLocation)
    {
        this.userLocation = _currentLocation;
        this.cheapRuler = new Geo.CheapRuler(userLocation.x, Geo.CheapRulerUnits.Meters);
    }

    // Interface IComparer<FeedData> implementation
    int IComparer<FeedData>.Compare(FeedData _feedA, FeedData _feedB)
    {
        int _comparision = cheapRuler.Distance(_feedA.Location, userLocation)
                                .CompareTo(cheapRuler.Distance(_feedB.Location, userLocation));
        return _comparision;
    }

}

Objective

Without using System.Linq how can I sort a HashSet<FeedData>

Reason for using HashSet opposed to another collection (say List) is at any time the count of FeedData could be significantly higher that performance would be in check. [HashSet vs. List performance ]

Other Operations on HashSet

  • Insert/Add FeedData
  • Removal of an item

Thank you!

Filip
  • 155
  • 2
  • 14

1 Answers1

0

HashSet cannot be sorted. An alternative collection type is SortedSet, which can be instantiated by a comparator object that implements the ICompare interface. Other possible alternative collection types are: SortedList, SortedDictionary

SortedSet

xiangbin.pang
  • 319
  • 1
  • 7