Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast insert in Link-like object

Tags:

c#

object

In a real-time Agent-based modelling project I have the following problem: Assume I have some class MyClass with a public proporty X (X is a double). I need a class (call it FancyList) that can contain my objects in a sorted manner. If I insert a new MyClass-object it should be inserted between an object with a lower X and one with a higher 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

It is important that the insert is as fast as possible.

like image 579
Peter Stephensen Avatar asked Feb 17 '26 12:02

Peter Stephensen


1 Answers

Use a SortedList<> or a SortedDictionary<>.

They both implement IDictionary. According to the MSDN docs the SortedDictionary has the faster Insert operation. Do read the rest of those specs.

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);
like image 152
Henk Holterman Avatar answered Feb 19 '26 00:02

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!