tags:

views:

97

answers:

4

Hi, at the moment I'm using a List<short> as a buffer to hold things for a while while a calculation is made to each value based on other values further down the buffer. I then realised that this probably wasn't very effecient as I have been told that List<> is a linked list so every time I do whatever = myList[100]; the poor thing is having to jump down all the other nodes first to get to the value I want. I dont want to use a regular Array because I have got loads of Add() and Remove()s kicking around in other places in the code. So I need a class that inherits IList<T> but uses a regular array data structure. Does anyone know a class in .net that works this way so I dont have to write my own? I tried using ArrayList but it 'aint generic!

+6  A: 

List<T> doesn't use a linked list implementation. Internally it uses an array, so it appears to be exactly what you need. Note that, because it's an array, Remove/insert could be an expensive operation depending on the size of the list and the position item being removed/inserted - O(n). Without knowing more about how you are using it, though, it's hard to recommend a better data structure.

Quoting from the Remarks section of the docs.

The List(T) class is the generic equivalent of the ArrayList class. It implements the IList(T) generic interface using an array whose size is dynamically increased as required.

tvanfosson
+1  A: 

No, a List<T> is a generic collection, not a linked list. If you need add and remove functionality then List<T> is the best type to use. I believe the CLR is optimised to handle them so performance need not be a concern.

David Neale
ok, thanks my idea that a List<> is a linked list was wrong :(
Ciemnl
if thats the case is there any reason for the use of a regular array over the list?
Ciemnl
thecoop
-1er. Why the mark-down?
David Neale
"optimised" is a bit of a joke :p. The List's internal array is initially allocated with 4 elements, and each time it's capacity is exceeded, a new array is allocated with double the previous size - and it's contents copied over. It's obviously not the best container for appending - it's just simpler to write than manually expanding arrays. The List<> is the analog of a C++ std::vector<>.
Mark H
+1  A: 

List<T> is backed by an array, not a linked list. Indexed accesses of a List<T> happen in constant time.

JSBangs
+2  A: 

In addition to tvanfosson's correct answer, if you're ever unsure of how something works internally, just load up the .NET Reflector and you can see exactly how things are implemented. In this case, drilling down to the indexer of List<T> shows us the following code:

public T this[int index]
{
    get
    {
        if (index >= this._size)
        {
            ThrowHelper.ThrowArgumentOutOfRangeException();
        }
        return this._items[index];
    }
    // ...

where you can see that this._items[index] is an array of the generic type T.

John Rasch