tags:

views:

113

answers:

4

Using Hashtable I want to have multiple objects mapped to the same key. E.g. 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. e.g. 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!

+3  A: 

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

thelost
Hashtable isn't generic, Dictionary<key, List<value>> does the same and saves you some casting.
Josh Sterling
I have a type that I call Index that is essentially a wrapped version of this.
Joshua
+7  A: 

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.

Justin Niessner
Why not use an `ISet` instead of `List`?
Hamish Grubijan
@Hamish - In this case, I'm using var to hold the value. I need concrete types on the right side of the assignment.
Justin Niessner
@Hamish it would depend completely on his implementation of student. For instance 2 Students can have the same name. On the converse he could use the ID of the student and compare the 2 values before inserting them.
Woot4Moo
A: 

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.

casperOne
+1  A: 

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.

Ani