65.9K
CodeProject is changing. Read more.
Home

SparseArray for C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.43/5 (10 votes)

Mar 19, 2002

viewsIcon

86709

downloadIcon

1555

A class that supports sparse arrays

I needed to store information in a grid similar to Excel where I did not want to restrain the user to a fixed multidimensional array that would be mostly unpopulated. Taking a page from NTFS, I decided to create a sparse array.

This array supports the bulk of those things that are supported by the System.Array class. Under the hood, it is using a hash table to store the elements with the index being the key.

Following is an example of how to use the SparseArray class.

// Create a 2 dimensional array
SparseArray array = new SparseArray(2);

// Set elements
array[3, 3] = "Hello";
array[9, 417] = "Nothing";

// Check bounds
int b;
b = array.GetLowerBound(0); // returns 0
b = array.GetLowerBound(1); // returns 0
b = array.GetUpperBound(0); // returns 9
b = array.GetUpperBound(1); // returns 417
b = array.Count; // returns 2

// Retrieve elements
object o = null;
o = array[3, 3]; // returns "Hello"
o = array[1, 1]; // returns null
o = array[9, 417]; // returns "Nothing"

// Walk the array elements
IEnumerator en = array.GetEnumerator();
while (en.MoveNext())
   o = en.Current;