tmcallaghan
tmcallaghan

Reputation: 1302

c# accessing hashtable of two-dimensional arrays

I've created a hashtable of two-dimensional arrays in c# and cannot figure out how to directly access the array values, the following is my current code:

// create the hashtable
Hashtable hashLocOne = new Hashtable();

// add to the hashtable if we don't yet have this location
if (!hashLocOne.ContainsKey(strCurrentLocationId))
  hashLocOne.Add(strCurrentLocationId,new double[20, 2] { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } });

// add to the value at a given array position, this does not work
hashLocAll[strReportLocationId][iPNLLine, 0] += pnl_value;

Upvotes: 1

Views: 4346

Answers (4)

nothrow
nothrow

Reputation: 16168

((double[,])hashLocAll[strReportLocationId])[iPNLLine, 0] += pnl_value;

Why dont you use Dictionary<string, double[,]> ?

Upvotes: 4

Jerry
Jerry

Reputation: 4547

So, you have a hashtable. You now want to get at that information.

It looks like hashLocAll should be hashLocOne. However, I'm guessing you have a reason for that.

With hashtables, everything inside is of type "object". Which means you have to do alot of casting.

Try this:

((double[,])hashLocOne[strReportLocationId])[iPNLLine, 0] += pnl_value;

Upvotes: 0

yfeldblum
yfeldblum

Reputation: 65435

  • I don't see any definitions for hashLocAll or strReportLocationId in your sample code.
  • You are using a non-generic dictionary. Use a generic dictionary instead.
  • You are using a bastardized version of Hungarian Notation. Don't do that. Get rid of the prefixes hash, str, i, etc. They are completely unnecessary in a language like C# and only make your code more difficult to read.

Upvotes: -2

John Feminella
John Feminella

Reputation: 311536

The Hashtable doesn't know what kind of objects are stored in it; you have to manually cast each one:

double result = ((double[,]) table["foo"])[4][5];

You should use a Dictionary instead of a Hashtable if possible:

var dict = new Dictionary<String, double[,]>();
double result = dict["foo"][4][5];

Upvotes: 5

Related Questions