简体   繁体   中英

Operations on Hashtable in C#

Using Hashtable I want to have multiple objects mapped to the same key. Eg Key is 'Age' and Values are ojects of struct 'Student'.

I suppose perceptually there will be a sort of linked list with Key acting as a 'Head' 25->obj1->obj2->obj3

Here are my questions:

Is the above representation correct? If not, which data structure can be used for achieving the same?

Can I look up for a specific field on the above data representation. eg One I reach the key 25, I look for the name 'Scott' in the row. Will I be able to stop/ get a pointer to the object containing the field Scott?

Thanks!

If you're using C#, the best option would probably be (which, essentially, is what you're proposing):

var collection = new Dictionary<Age, List<Student>>();

Assuming Age and Student are both types.

Only one value can be stored for a key. So how about Hashtable<int, List<Student>> ?

If you already have a collection of all the students at the time you want to create this data-structure, you could do

var lookUp = Students.ToLookUp (student => student.Age);

The disadvantage is that the Lookup <K,V> data-structure is immutable. If this is not an option, a Dictionary<int, List<Student>> structure might be more appropriate as others have mentioned.

There is no wrong data structure to use here, just some structures to store will be better suited for your needs depending on what you want to do with the results that are keyed on the age.

You indicated you wanted the ability to perform a lookup on the items based on name once you get the students that are a particular age. In this case, your would want to have an IDictionary<string, Student> where the key is the first name of the Student.

Note, that this is a highly specialized structure here. If it keeps expanding to where you need to search on other facets, you might want to take a look at other options, as the code required would grow pretty unmaintainable as your selection criteria grew.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM