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?
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>.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With