Ivan Ivan - 1 month ago 16
C# Question

What type is the best for loose numerically-indexed lists in C#?

What I need is something like an array but letting me to assign an element to whatever an index at any time and check if there is already a value assigned to particular index approximately like

MyArray<string> a = new MyArray<string>();
a[10] = "ten";
bool isTheFifthElementDefined = a[5] != null; // false


Perhaps
Dictionary<int, string>
with its
ContainsKey
method could do, but isn't there a more appropriate data structure if I want an ordered collection with numeric keys only?

I am also going to need to iterate through the defined elements (with foreach or linq preferably) accessing both the value and the key of current element.

Answer

As you mentioned Dictionary seems more appropriate for this.But you can do it with generic lists,for example, when you are creating your list you can specify an element count,and you can give a default temporary value for all your elements.

List<string> myList = new List<string>(Enumerable.Repeat("",5000));
myList[2300] = "bla bla bla..";

For int:

List<int> myList = new List<int>(Enumerable.Repeat(0,5000));

For custom type:

List<MyClass> myList = new List<MyClass>(Enumerable.Repeat(new MyClass(), 100));

Ofcourse It is not the best solution...

Note: Also you can use SortedList instead of Dictionary if you want an ordered collection by keys:

SortedList<TKey, TValue> : Represents a collection of key/value pairs that are sorted by key based on the associated IComparer implementation.

Comments