Hashtable ht = new HashTable();
ht["LSN"] = new string[5]{"MATH开发者_开发技巧","PHIS","CHEM","GEOM","BIO"};
ht["WEEK"] = new string[7]{"MON","TUE","WED","THU","FRI","SAT","SUN"};
ht["GRP"] = new string[5]{"10A","10B","10C","10D","10E"};
now i want to get values from this ht like below.
string s = ht["LSN"][0];
but it gives error. So how can i solve this problem.
I think you want to use a generic typed Dictionary rather than a Hashtable:
Dictionary<String, String[]> ht = new Dictionary<string, string[]>();
ht["LSN"] = new string[5] { "MATH", "PHIS", "CHEM", "GEOM", "BIO" };
ht["WEEK"] = new string[7] { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
ht["GRP"] = new string[5] { "10A", "10B", "10C", "10D", "10E" };
string s = ht["LSN"][0];
This should compile fine.
Otherwise you need to perform a cast such as:
string s = ( ht[ "LSN" ] as string[] )[ 0 ];
Hashtable stores untyped objects: you'd need to re-cast the value you read back into a string array, e.g.
string s = ((string[])ht["LSN"])[0];
or
string s = (ht["LSN"] as string[])[0];
However you're better off using something typed, e.g. a Dictionary<>
- then it'll just work:
Dictionary<string, string[]> ht = new Dictionary<string, string[]>();
...
string s = ht["LSN"][0];
Your hashtable is of type object, so when you try to access the array, you will get an error since object does not support the array accessor syntax you are using. if you used a dictionary, as explained in other answers, you could use generics to define that you are using string arrays rathe than objects, which will work as you wish.
alternatively, you can cast your variables like this:
string[] temp = (string[])ht["LSN"];
this will give you the access to temp that you desire.
your ht["LSN"][0]
will return you a string array. so you have to add another indexer to get proper value.
((string[])ht["LSN"][0])[0]
Since Hashtable
contents are exposed as object
you would need to cast:
string s = (ht["LSN"] as string[])[0];
But you would probably be better off using a strongly-typed container as suggested by Nick.
The indexer of the HashTable
class always returns an instance of object
. You'll have to cast that object to an array of strings:
string s = ((string[]) ht["LSN"])[0];
That said, consider using the generic Dictionary<TKey, TValue>
class instead.
string[] aStrings = (string[])ht["LSN"];
string s = aStrings[0];
精彩评论