HashSet 使用自定义IComparer排序而不使用LINQ

问题描述 投票:-1回答:1

场景

我有一个自定义类(称为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>进行排序

与其他集合(例如List)相对的

使用HashSet的原因在任何时候FeedData的计数都可能明显高于检查性能。[HashSet vs. List performance]

HashSet上的其他操作

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

谢谢!

c# collections interface hashset icomparer
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.