If most of your elements are null, then you probably don't need to create an array at all.
John offers one approach that will work - implementing a sparse array using linked lists. Here is another:
public struct CellLocation { int Row; int Column; } public class Element { public Element(int row, int column) { Location = new CellLocation {Row = row, Column=column}; } public readonly Location { get; private set; }
Now you can store Element objects in Dictionary<CellLocation, Element> . In fact, I would put this dictionary in my own class so that it can implement methods such as:
public IEnumerable<Element> AdjacentElements(Element elm) { for (int row = -1; row <= 1; row++) { for (int column = -1; column <= 1; column++) {
There are operations for which this can be faster than a sparse array. To find an element in one row and column, a sparse array still has to do a linear search to find a row, and then another linear search to find a column in that row, while this method can find an element with one search in the hash table.
There are also circumstances in which it will be significantly slower. To find all the elements in a row, it takes as many hash table queries as there are cells in the row, and when using a sparse array, the linked list simply moves.
source share