【问题标题】:Fast insert in Link-like object快速插入类链接对象
【发布时间】:2014-07-05 22:56:10
【问题描述】:

在一个基于代理的实时建模项目中,我遇到了以下问题:假设我有一些 MyClass 类,它具有公共比例 X(X 是双精度)。我需要一个可以以排序方式包含我的对象的类(称为 FancyList)。如果我插入一个新的 MyClass 对象,它应该被插入一个具有较低 X 的对象和一个具有较高 X 的对象之间。

FancyList _fancyList = new FancyList();

// Allocate MyClass objects. The X proporty is defined in the constructor
MyClass c1 = new MyClass(2.0)
MyClass c2 = new MyClass(3.0)
MyClass c3 = new MyClass(2.5)

_fancyList.Insert(c1);
_fancyList.Insert(c2);
_fancyList.Insert(c3);

// In the fancyList c3 is after c1 and before c2. Therefore c1 is the first
// element, and c2 is the last element

插入尽可能快是很重要的。

【问题讨论】:

    标签: c# object


    【解决方案1】:

    使用SortedList<> 或SortedDictionary<>。

    它们都实现了IDictionary。根据the MSDN docs,SortedDictionary 具有更快的插入操作。请阅读其余的规格。

    FancyList _fancyList = new SortedDictionar<double, MyClass>();
    
    // Allocate MyClass objects. The X proporty is defined in the constructor
    ...
    
    _fancyList.Insert(c1.X, c1);
    _fancyList.Insert(c2.X, c2);
    _fancyList.Insert(c3.X, c3);
    

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 2020-08-20
      • 2016-12-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      相关资源
      最近更新 更多