使用自定义IComparer排序而不使用LINQ的HashSet <T>

时间:2019-11-29 02:10:03

标签: c# collections interface hashset icomparer

场景

我有一个自定义类(称为FeedData),该类将收集在HashSet<FeedData>

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

我现在有了一个自定义IComparer,它将有助于对HashSet<FeedData>进行从最接近用户位置到最远位置的排序。比较发生在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;
    }

}

客观

不使用System.Linq怎么对HashSet<FeedData>进行排序

使用HashSet 而不是另一个集合(例如List)的原因是,在任何时候FeedData的计数都可能明显高于检查性能。 [HashSet vs. List performance]

HashSet上的其他操作

  • 插入/添加FeedData
  • 删除项目

谢谢!

1 个答案:

答案 0 :(得分:0)

HashSet无法排序。 另一种收集类型是SortedSet,它可以由实现ICompare接口的比较器对象实例化。 其他可能的替代集合类型是:SortedList,SortedDictionary

SortedSet