Dictionary<Units, Dictionary<Units, double>> is not really satisfactory
because, in general, you need to explicitly create Dictionary<Units,double>
and (worse), if you want to add to P2P_[Units.Pa] you must first check
whether or not it exists because it is a reference type.
There are three solutions - the first gives you the syntax that you want but
is quite tedious to code:
1) Create a struct StructDictionary<K,V> implementing IDictionary<K,V> that
lazily creates a Dictionary<K,V> and delegates everything to it. Then use
Dictionary<Units,StructDictionary<Units,double>>.
The second is shorter and more efficient but does have slightly different
capabilities and syntax.
2) Create a struct Pair<K1,K2> with Equals and GetHashCode overrides and use
Dictionary<Pair<Units,Units>,double>. This seems to give what you are
actually trying to do which is a unit conversion table.
In either case you should probably be hiding the whole thing in a class with
"double Convert(Units fromUnits,Units toUnits,double value)"
Note also that to be able to do all conversions you need a delegate rather
than a double since otherwise you cannot convert from centigrade to either
Fahrenheit or Kelvin. Alternatively conversions of the form y = mx+c can be
handled by a two part structure holding m and c. The data approach has the
advantage that you only need to populate the conversion one way - if the
conversion method can't find Fahrenheit to centigrade it can look up
centigrade to fahrenheit and invert it.
For maximum flexibility you should use strings rather than enums so that you
can load conversions from a database or file. (use static strings for
hardwired stuff)
"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote in message
news:ON**************@TK2MSFTNGP03.phx.gbl...
"Torben Laursen" <To****@newsgroups.nospam> a écrit dans le message de
news:
e9**************@TK2MSFTNGP04.phx.gbl...
| I looked at that but I need a way to get a 2D map.
| This is my C++ code:
| enum Units {Pa=0, Bar, Atm, kPa, Psi, MPa};
| std::map<Units, std::map<Units, double> > P2P_;
|
| Then I can use P2P_ as: P2P_[Pa][Bar] where it returns a double
|
| It there a way to do this in C#?
How about Dictionary<Units, Dictionary<Units, double>> ??
public enum Units
{
Pa = 0, Bar, Atm, kPa, Psi, MPa
}
class Program
{
static void Main(string[] args)
{
Dictionary<Units, Dictionary<Units, double>> p2p = new
Dictionary<Units,Dictionary<Units,double>>();
Dictionary<Units, double> newEntry = new Dictionary<Units,double>();
newEntry.Add(Units.Atm, 12.34);
p2p.Add(Units.Pa, newEntry);
double result = p2p[Units.Pa][Units.Atm];
System.Console.WriteLine(result);
System.Console.ReadLine();
}
}
Joanna
--
Joanna Carter [TeamB]
Consultant Software Engineer