Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help with HashTables which contents string arrays in C#


I have a code like this.

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.

like image 632
namco Avatar asked Feb 15 '11 09:02

namco


1 Answers

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 ];
like image 143
Nick Avatar answered Sep 24 '22 00:09

Nick