Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique integer from string?

Tags:

c#

.net

I have a few classes with heterogenous keys - int and string - and i want to work with them through common interface. It's pretty simple just convert int to string but it obviously will cause perfomance issues. Another options I see are box them to "object", which also doesn't seems perfect, or somehow generate unique integers from string (there will be no joins between former "string" and "int" so they must be unique only in "string" domain) and the quetsion here is "how"?

like image 551
Yan Avatar asked Jun 05 '12 15:06

Yan


2 Answers

Just take string.GetHashCode() which returns an int from a string with very low collision probability.

like image 116
Tudor Avatar answered Sep 19 '22 09:09

Tudor


As @tudor pointed out GetHashCode is the supported way of producing hash code from strings (and other objects). Unfortunately there is no way to do such transformation so an integer represent unique strings unless you put severe restrictions on set of strings.

I.e. if your strings short enough (i.e. 2 Unicode or 4 ASCII characters) than there is obvious one-to-one mapping, or if your set of strings is limited and known in advance.

Some reading on the subject: the underlying problem called pigeonhole principle which guarantees collision. Due to Birthday paradox collisions are very likely to happen on reasonably small sets.

like image 24
Alexei Levenkov Avatar answered Sep 20 '22 09:09

Alexei Levenkov