【问题标题】:HashSet<T> to be sorted using a custom IComparer without using LINQHashSet<T> 使用自定义 IComparer 进行排序,而不使用 LINQ
【发布时间】:2020-03-24 15:35:16
【问题描述】:

场景

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

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

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

使用 HashSet 的原因 与另一个集合(例如 List)相对,是任何时候 FeedData 的计数都可能显着高于性能受到控制的情况。 [HashSet vs. List performance]

HashSet 上的其他操作

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

谢谢!

【问题讨论】:

    标签: c# collections interface hashset icomparer


    【解决方案1】:

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

    SortedSet

    【讨论】:

      猜你喜欢
      • 2010-11-02
      • 2010-11-29
      • 2012-12-29
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多