Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object by hashcode

Tags:

c#

hashcode

hash

I don't understand why there isn't a native function to do this. Suppose that I create the following class:

public class Student {
     public string Name {get; set;}
     public override int GetHashCode() {
         return(Name.GetHashCode());
     }
}

Afterwards, I create a HashSet containing a number of students. Now I want to get a student from the HashSet using his name, which is also the hash code used, without enumeration. Is this possible? If it is, how would I accomplish this? Since the name of the student is used as the hash code, this should be possible with an O(1) operation, right?

like image 812
Orestis P. Avatar asked Jan 21 '26 23:01

Orestis P.


2 Answers

A hashcode is not a unique identifier. Different objects may have the same hashcode. The only requirement for hashcodes is that objects that are considered equal have the same hashcode.

If you need O(1) retrieval of an item based on a key, use a Dictionary<TKey, TValue>, not a HashSet<T>.

like image 77
Thomas Levesque Avatar answered Jan 24 '26 20:01

Thomas Levesque


Instead of using a HashSet (or a Dictionary) to store your students use a KeyedCollection instead.

public class StudentCollection : KeyedCollection<string, Student>
{
    protected override string GetKeyForItem(Student item)
    {
        return student.Name;
    }
}

This will let you do lookups by name quickly just like a Dictionary but you don't need to manually pair up the name with the key when you are inserting. But be aware, no two students can have the same name or you will get a error (just the same as if you had a Dictionary and used two students of the same name).

like image 33
Scott Chamberlain Avatar answered Jan 24 '26 19:01

Scott Chamberlain