[Simple] How to retrieve the Hashtable value, stored in a list?
Hello, guys! Could you please help me with retrieving the value of a key, contained in a list? Here is the script:
public Hashtable all_containers_hashtable = new Hashtable();
public List<string> container_list_1 = new List<string>();
public List<string> container_list_2 = new List<string>();
// Start is called before the first frame update
void Start()
{
container_list_1.Add("name_1");
container_list_1.Add("description_1");
container_list_1.Add("param_1_1");
container_list_1.Add("param_1_2");
container_list_1.Add("param_1_3");
all_containers_hashtable.Add("card_1", container_list_1);
container_list_2.Add("name_2");
container_list_2.Add("description_2");
container_list_2.Add("param_2_1");
container_list_2.Add("param_2_2");
container_list_2.Add("param_2_3");
all_containers_hashtable.Add("card_2", container_list_2);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Q)) {
Debug.Log(all_containers_hashtable["container_list_1"]);
//returns the type: List
Debug.Log(all_containers_hashtable["container_list_1"][1]);
// D o e s n ' t w o r k (intended, it will return "description_1"), instead it gives error
}
}
Answer by Dragate · Jul 20, 2019 at 03:24 PM
The hashtable doesn't have a "container_list_1" key. That is a value corresponding to the "card_1" key. Also, since hashtables can receive values of all types without pre-defining (in contrast to dictionaries), you need to typecast your value to access its elements.
List<string> list = (List<string>) all_containers_hashtable ["card_1"]; // Get list by typecasting
Debug.Log(list[1]); // Access the 2nd element of the list
Thank you! It works! P.S. That solution requires the declaration (typecasting) of another variable - i.e. "list". Which increases the variable count in the script. Is there a way to get the element without that - another variable?
It's just a local declaration. In one line it would be:
Debug.Log(((List<string>) all_containers_hashtable ["card_1"])[1]);
It still would unbox the whole list temporarily to get hold of the element you want to access.