I have a class Foo
which contains a list of objects: List<Bar>
. Each Bar
has a property which they can be ordered on (of type TimeSpan
, representing a duration), and Bar
is an immutable object - that is, the duration does not change over the running of the algorithm. At the moment, for each Foo
I also maintain the Bar
that would be first in the list if it were to be ordered (i.e. the Bar
of shortest duration). Something like this:
public class Foo
{
public List<Bar> AllBars { get; set; }
public Bar FirstBar { get; set; }
public Foo (Bar bar)
{
FirstBar = bar;
AllBars = new List<Bar>() { bar };
}
public AddBar(Bar bar)
{
if(bar.Duration < FirstBar.Duration)
{
FirstBar = bar;
}
AllBars.Add(bar);
}
}
This class Foo
is used in an algorithm where processing performance (speed) is critical. Memory is important but not as much as speed. There is a list of n Foo
s, each of which has up to m Bar
s. This class has served me well up until this point. I now wish to offer the user several choices, meaning I will need to provide random access to the first few Bar
s in the list.
I would thus like to store my Bar
s in order so that I can access them by index in order. In my Bar
class I implemented IComparable
to allow Bar
s to be compared on duration but I am stuck at choosing an appropriate data type. I looked at System.Collections.SortedList
but (unless I am wrong) this appears to reference elements by key as it implements IDictionary
. What collection could I use that would maintain my objects such that they stay sorted, and such that they are traversable in order of index?
By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.
util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
Use the associative container set , declared in <set> , which stores items in sorted order.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
I prefer to use SortedSet<T>
, which is a binary tree where the key and value are the same object. This once again means that adding/removing/lookups are logarithmic - O(log n)
- but you gain the ability to iterate over the items in order. For this collection to be effective, type T
must implement IComparable<T>
or you need to supply an external IComparer<T>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With