I have an issue where I need to map two inputs to a single output.
I'm aware that a dictionary is a generically typed linear mapping:
for every x (
key
) there may be a y (value
)
What I need is a multi-dimensional mapping:
for every x,y (
key
) there may be a z (value
)
But of course the kicker is that I need it to support generic typing and be dynamically sized.
Does this data-structure exist in C#, or do I have to create a dictionary of dictionaries? I'd rather not reinvent the wheel if I don't have to.
using System;
using System.Collections.Generic;
using System.Text;
namespace zlib.Collections
{
public class Dictionary3D<Tx, Ty, Tz>
{
private Dictionary<Tuple<Tx, Ty>, Tz> _dict = new Dictionary<Tuple<Tx, Ty>, Tz>();
public void Add(Tx x, Ty y, Tz z)
{
_dict.Add(Tuple.Create<Tx, Ty>(x, y), z);
}
public void Clear()
{
_dict.Clear();
}
public bool ContainsKey(Tx x, Ty y)
{
return _dict.ContainsKey(Tuple.Create<Tx, Ty>(x, y));
}
public bool ContainsValue(Tz z)
{
return _dict.ContainsValue(z);
}
public Dictionary<Tuple<Tx, Ty>, Tz>.Enumerator GetEnumerator()
{
return _dict.GetEnumerator();
}
public bool Remove(Tx x, Ty y)
{
return _dict.Remove(Tuple.Create<Tx, Ty>(x, y));
}
public bool TryGetValue(Tx x, Ty y, out Tz z)
{
return _dict.TryGetValue(Tuple.Create<Tx, Ty>(x, y), out z);
}
public int Count
{
get { return _dict.Count; }
}
public Dictionary<Tuple<Tx,Ty>,Tz>.KeyCollection Keys
{
get
{
return _dict.Keys;
}
}
public Dictionary<Tuple<Tx, Ty>, Tz>.ValueCollection Values
{
get
{
return _dict.Values;
}
}
public Tz this[Tx x, Ty y]
{
get
{
return _dict[Tuple.Create<Tx, Ty>(x, y)];
}
set
{
_dict[Tuple.Create<Tx, Ty>(x, y)] = value;
}
}
}
}
It seems like reinventing the wheel is winning out among responses. This is the code I've come up with so far, but I feel like there should be a better way, like a matrix
or something.
what about
Dictionary<Tuple<T,K>,Tuple<L,J>>
??
If I get you right, that is what you need:
class Key<Tx, Ty>
{
public Tx x;
public Ty y;
public Key(Tx x, Ty y)
{
this.x = x;
this.y = y;
}
}
Dictionary<Key<Tx, Ty>, Tz> d;
And yes, how mentioned in a comment, you gotta implement HashCode and Equals in that Key class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With