Baruch
Baruch

Reputation: 21538

Non-consecutive numbered array .NET

What collection type would I use in C# for an array where the indexes are non-consecutive (but are only added in ascending order), and I need access both by index and by place (e.g. "consecutive index")?

For example, if I add the objects A, B and C with indexes 2, 4 and 7, I need to access by index (2/4/7) or by place (1/2/3 or 0/1/2 both work).

Upvotes: 1

Views: 920

Answers (2)

Joe
Joe

Reputation: 47719

You should use a Dictionary to store the objects for access by their index, but you'll also need some kind of List to store the 'place' as Dictionary doesn't store place. Join these together in your own class and handle adding as one operation to make sure they are in sync.

If you only want to use one, you can use the List and loop over it to look up the key, but it will take linear O(N) time.

Edit

As Matthew Strawbridge points out, the BinarySearch method will find the element in O(log N) so you can skip using the dictionary.

Upvotes: 2

marsze
marsze

Reputation: 17124

Use a Dictionary:

using System.Collections.Generic;

Dictionary<int, type> dict = new Dictionary<int, type>();

// Add values:
dict.Add(2, A);
dict.Add(4, B);
dict.Add(7, C);

// by index:
var A = dict[2];
var B = dict[4];
var C = dict[7];

// by place:
var A = dict.ElementAt(0);
var B = dict.ElementAt(1);
var C = dict.ElementAt(2);

Upvotes: 1

Related Questions