Home
Manage Your Code
Snippet: SparseArray (C#)
Title: SparseArray Language: C#
Description: Implements a simple sparse array in C# Views: 482
Author: Stephen Smith Date Added: 8/3/2012
Copy Code  
1    internal class SparseArray<T>
2    {
3        // Master dictionary hold rows of data

4        protected Dictionary<int, T> _rows;
5
6        /// <summary>

7        /// Constructs a SparseArray instance.

8        /// </summary>

9        public SparseArray()
10        {
11            _rows = new Dictionary<int, T>();
12        }
13
14        /// <summary>

15        /// Gets or sets the value at the specified matrix position.

16        /// </summary>

17        /// <param name="row">Matrix row</param>

18        public T this[int row]
19        {
20            get
21            {
22                return GetAt(row);
23            }
24            set
25            {
26                SetAt(row, value);
27            }
28        }
29
30        /// <summary>

31        /// Determine if the <em>SparseArray</em> has data at the specified row

32        /// </summary>

33        /// <param name="row">The data-row to query</param>

34        /// <returns>

35        /// true if valid data is held at the row otherwise, false

36        /// </returns>

37        public bool HasDataAt(int row)
38        {
39            return _rows.ContainsKey(row);
40        }
41
42        /// <summary>

43        /// Gets the value at the specified matrix position.

44        /// </summary>

45        /// <param name="row">Matrix row</param>

46        /// <returns>Value at the specified position</returns>

47        public T GetAt(int row)
48        {
49            T result;
50            if (_rows.TryGetValue(row, out result)) return result;
51            return default(T);
52        }
53
54        /// <summary>

55        /// Sets the value at the specified matrix position.

56        /// </summary>

57        /// <param name="row">Matrix row</param>

58        /// <param name="value">New value</param>

59        public void SetAt(int row, T value)
60        {
61            if (EqualityComparer<T>.Default.Equals(value, default(T)))
62            {
63                // Remove any existing object if value is default(T)

64                RemoveAt(row);
65            }
66            else
67            {
68                _rows[row] = value;
69            }
70        }
71
72        /// <summary>

73        /// Clear all data out of the <em>SparseArray</em>.

74        /// </summary>

75        public void Clear()
76        {
77            _rows.Clear();
78        }
79
80        /// <summary>

81        /// Removes the value at the specified matrix position.

82        /// </summary>

83        /// <param name="row">Matrix row</param>

84        public void RemoveAt(int row)
85        {
86            _rows.Remove(row);
87        }
88    }
Notes
Inspired by http://www.blackbeltcoder.com/Articles/algorithms/creating-a-sparse-matrix-in-net