Ivan
Ivan

Reputation: 64207

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.

Upvotes: 0

Views: 115

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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.

Upvotes: 2

pid
pid

Reputation: 11597

If you need key/value pairs you cannot use a list, you'll need a Dictionary. The implementation is pretty snappy so don't be too afraid about performance (as long as you don't put too much values in it).

You can iterate over it with

foreach(KeyValuePair<int, string> kvp in dict)
{
}

If you need to order it you can use a list:

List<int> ordered = new List(dict.Keys);
ordered.Sort();

foreach(int key in ordered)
{
}

Upvotes: 1

Related Questions