C# HashSet<;T>;在不使用LINQ的情况下使用自定义IComparer进行排序

C# HashSet<;T>;在不使用LINQ的情况下使用自定义IComparer进行排序,c#,collections,interface,hashset,icomparer,C#,Collections,Interface,Hashset,Icomparer,场景 我有一个自定义类(称为FeedData),它将收集在HashSet 我现在有了一个自定义的IComparer,它可以帮助将HashSet从最近到最远的位置排序到用户的位置。比较发生在FeedData.Location internal sealed class DistanceComparer : IComparer<FeedData> { private CheapRuler cheapRuler; private Vector2d userLocation

场景

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

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

}
内部密封类距离比较器:IComparer
{
私人小气鬼小气鬼;
私有向量2D用户位置;
//建造师
内部距离比较器(矢量2D\u当前位置)
{
this.userLocation=\u currentLocation;
this.cheapRuler=new Geo.cheapRuler(userLocation.x,Geo.CheapRulerUnits.Meters);
}
//接口IComparer实现
int IComparer.比较(FeedData\u feedA,FeedData\u feedB)
{
int\u comparison=cheapRuler.Distance(\u feedA.Location,userLocation)
.CompareTo(cheap尺子距离(_feedB.Location,userLocation));
返回-比较;
}
}
目标

如果不使用
System.Linq
如何对
HashSet

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

哈希集上的其他操作

  • 插入/添加
    FeedData
  • 删除项目
谢谢大家!

无法对哈希集进行排序。 另一种收集类型是SortedSet,它可以由实现ICompare接口的comparator对象实例化。 其他可能的替代收集类型有:SortedList、SortedDictionary

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;
    }

}