1

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;

4 Answers 4

5

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];
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

0

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;

Comments

-2
  • 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.

1 Comment

This really doesn't help answer the question, and your last two points make me wish you could delete answers as "subjective and argumentative".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.