Help with HashTables which contains string arrays in C #


I have such a code.

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 the values ​​from this ht as below.

 string s = ht["LSN"][0]; 

but he gives an error. So how can I solve this problem.

+7
source share
7 answers

I think you want to use a typical typed dictionary, not 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 do a listing, for example:

 string s = ( ht[ "LSN" ] as string[] )[ 0 ]; 
+8
source

Hashtable stores untyped objects: you will need to re-convert the value you are reading into a string array, for example.

 string s = ((string[])ht["LSN"])[0]; 

or

 string s = (ht["LSN"] as string[])[0]; 

However, you are better off using something printed, for example. a Dictionary<> - then it will work:

 Dictionary<string, string[]> ht = new Dictionary<string, string[]>(); ... string s = ht["LSN"][0]; 
+2
source

Your hash table has an object type, so when you try to access an array, you will get an error because the object does not support the syntax of access to the array that you are using. if you used a dictionary, as explained in other answers, you can use generics to determine if you are using rathe string arrays than objects that will work as you wish.

alternatively, you can use your variables as follows:

 string[] temp = (string[])ht["LSN"]; 

this will give you access to the pace you desire.

+2
source

your ht["LSN"][0] will return you an array of strings. so you need to add another index to get the correct value.

 ((string[])ht["LSN"][0])[0] 
+1
source

Since the contents of the Hashtable displayed as object , you will need to use:

 string s = (ht["LSN"] as string[])[0]; 

But you probably would be better off using a strongly typed container, as suggested by Nick .

+1
source

The indexer of the HashTable class always returns an instance of object . You will need to pass this object to an array of strings:

 string s = ((string[]) ht["LSN"])[0]; 

However, use the generic Dictionary<TKey, TValue> .

+1
source
 string[] aStrings = (string[])ht["LSN"]; string s = aStrings[0]; 
+1
source

All Articles