The very simple solution I just made is this:
public class Sparse3DMatrix<T> { Dictionary<Tuple<int,int,int>, T> values = new Dictionary<Tuple<int, int, int>, T>(); public T this[int x, int y, int z] { get { return values[new Tuple<int, int, int>(x, y, z)]; } set { values[new Tuple<int, int, int>(x, y, z)] = value; } } public bool ContainsKey(int x, int y, int z) { return values.ContainsKey(new Tuple<int, int, int>(x, y, z)); } }
using:
var test = new Sparse3DMatrix<float>(); test[1, 1, 1] = 1f; Console.WriteLine(test[1, 1, 1]);
It can be expanded using methods similar to those that its version has, and with checks for x, y, z , etc.
I'm sure someone can say something about its performance. This will be a decent implementation if you really don't need something for high performance. It depends on the implementation of the Tuple hash code and your specific use. If we assume that the hashes are good, we will have O(1) search time. If you know that you will have many elements, you can use new Dictionary<...>(initial capacity) to avoid unnecessary resizing when adding elements.
Unlike him, this has only one Dictionary with all the elements. Its version has dictionaries of dictionaries. Its advantage, if you need to scan the entire row, you can simply repeat the second-level dictionary (this will not help you if you want to scan columns), which is faster than an individual element search. But having one dictionary means less memory - especially when you have few items in a row.