473,396 Members | 2,052 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Find key by value in Hashtable (or other)

Dan
I have the need to translate values back and forth. I have created a
Hashtable to do this because I don't care about intrinsic order and I
want it to be a fast as possible. My only concern is that I doubled
the size of my Hashtable to accommodate translating both ways. Kind of
like the following, but longer with more complicated data.

Hashtable ht = new Hashtable();
ht.Add("x1", "y1");
ht.Add("x2", "y2");
ht.Add("y1", "x1");
ht.Add("y2", "x2");

Basically, I have the feeling that this is a poor structure and I'm
missing the elegant solution that makes the above mini-example only 2
adds. To do this I would need 2 methods like the following:

val = ht.fromkey(obj key)
key = ht.fromval(obj val)

Is there some other collection that would better suit this? Is adding
each translation both ways wrong in some way?

These translation tables will not be very long. Therefore, this is
more a question of how to make the code cleaner (and me less bothered
by the inelegance) than performance.

-Dan

Nov 17 '05 #1
7 20093
Dan
Thank you for the responses. As per your suggestions I will make it 2
tables. When originally looking at it I considered 1 table vs. 2 to be
about equivalent and chose the one I though might consume a little less
resources.

Jon,
I would like to know why when a key is equal to a value it would cause
problems. In my case every key has an equivalent value (though no key
is equivalent to it's value). It always helps for the next problem to
have a little deeper understanding. If you have a sec could you post
why this would be the case.

Thanks again,
Dan

Nov 17 '05 #2
Dan,

The problem Jon is referring to may also raise its head with two hash
tables.

Will it ever be possible that you will have two keys with the same
value? Or two values with the same key? Either one of these situations
will cause trouble for you, because Hashtable retains only the last
entry you set for a given key. (Or, if you use the Add method, will
throw an ArgumentException if the key is already in the table.)

If you use only one table, and you have a pair with key "a1" and value
"a1" and you say:
ht.Add("a1", "a1");
ht.Add("a1", "a1");
then the second line will throw an ArgumentException because the key
"a1" is already in the hash table.

You will have a similar problem if you happen to have two keys with the
same value:
ht1.Add("k1", "v1");
ht2.Add("v1", "k1");
ht1.Add("k2", "v1");
ht2.Add("v1", "k2"); // will fail with an ArgumentException
there are ways to code so that the fourth line doesn't fail with an
ArgumentException, but then you'll lose the information that value v1
also has key k1, because the relationship between v1 and k2 will
overwrite the previous relationship.

If you're in a situation in which the same value can have multiple keys
(or the same key can have multiple values), then you have to use a
Hashtable of ArrayLists:

Hashtable htKeyToValue = new Hashtable();
Hashtable htValueToKey = new Hashtable();

// for each key "k" and value "v":
ArrayList valueList = (ArrayList)htKeyToValue["k"];
if (valueList == null)
{
// First time we've seen this key
valueList = new ArrayList();
htKeytoValue.Add("k", valueList);
}
valueList.Add("v");
ArrayList keyList = (ArrayList)htValueToKey["v"];
if (keyList == null)
{
// First time we've seen this value
keyList = new ArrayList();
htValuetoKey.Add("v", keyList);
}
keyList.Add("k");

Nov 17 '05 #3
Dan <da*************@yahoo.com> wrote:
Thank you for the responses. As per your suggestions I will make it 2
tables. When originally looking at it I considered 1 table vs. 2 to be
about equivalent and chose the one I though might consume a little less
resources.

I would like to know why when a key is equal to a value it would cause
problems. In my case every key has an equivalent value (though no key
is equivalent to it's value). It always helps for the next problem to
have a little deeper understanding. If you have a sec could you post
why this would be the case.


Okay, consider the situation where you have two different pairs, (x, y)
and (y, x). Using a one-table solution, the second pair to be added
would overwrite both entries of the first, despite it being a different
pair. Using a two-table solution, you end up with x->y and y->x in both
tables, each one representing a distinct pair.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4
Bruce Wood <br*******@canada.com> wrote:
The problem Jon is referring to may also raise its head with two hash
tables.


Actually, I was raising a slightly different problem. Having two pairs
with the same first part or with the same second part would indeed
cause problems whatever you do, but I was considering the situation
when there were two distinct pairs (x, y) and (y, x), which the two-
table solution can cope with, but the one-table solution can't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Dan
Thanks for the replies.

I understand Bruce's point, but in my situation I will not have
duplicate keys. I will have the situation Jon is describing for every
entry (every x->y has a y->x). So, the short answer is I will go to 2
tables. On the purely acedemic side, I have not seen the problem Jon
is refering to. The 1 table structure I have appears to be working
fine for both translations. Most failed translations would throw
exceptions based on the fact that x is a character and y is a number.
If i get back a char for y, the program will break. Just looking at
the text files for the reverse translation, I see all of the
charachters I'm looking for.

If x -> y is overwritten by y -> x that would imply to me (uninformed
as I may be) that somehow the keys and values were being stored in the
same structure. I thought all of the keys were stored as hashcodes and
associated with the reference to the value.

Nov 17 '05 #6
We had assumed that your keys and your values were of the same data
type. The relationship x->y _will_ overwrite y->x if you are hashing
each relationship in its original order and in its reverse order for
reverse lookup, so the relationship x->y results in _two_ entries in a
single hash table: x->y and y->x (for the reverse lookup). Then if you
have another key/value pair y->x you are in trouble. Of course, as I
said, this assumed that the keys and the values were of the same data
type, which in your case they're not. However, it's an odd design to
have a hash table with two different data types as keys.

You say that you won't have duplicate keys... but will you have
duplicate values? In other words, can you possibly have:

x -> y
z -> y

? If so, then you have to use the hash table of arrays for the reverse
lookup hash table, because you want to store the relationship

y -> x, z

Nov 17 '05 #7
Dan
Actualy the keys and values are all the same data type (string).
However, the y side is converted to an int by the class that is using
the hashtable. I have a converter class that can be called that wraps
up the Hashtable and other details of the conversion.

Some of the actual table:

//Positive 0 thru 9
chtConversionTable.Add("0", "{");
chtConversionTable.Add("1", "A");
....
//Negative 0 thru 9
chtConversionTable.Add("10", "}");
chtConversionTable.Add("11", "J");
....
//Reversed positive 0 thru 9
chtConversionTable.Add("{", "0");
chtConversionTable.Add("A", "1");
....
//Reversed negative 0 thru 9
chtConversionTable.Add("}", "10");
chtConversionTable.Add("J", "11");
....

Negative numbers have 10 added because there is a diference between -0
and +0 since they are trailing digits. Each no key is repeated and no
value is repeated. Keys have one and only one matching value that is
part of a seperate pair. Sorry if my posts were misleading.

Thanks,
Dan

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: pwnalwandi | last post by:
hi everyone out there can anyone give me the value of a(wn executed saperatly) initially a=5 a+=(a++)+(++a) a-=(--a)-(a--) support ur answers with reasons (precedence,assoivity) thanks in...
7
by: ad | last post by:
I have a hash table like: Hashtable myHT = new Hashtable(); myHT.Add("First", "Hello"); myHT.Add("Second", "World"); myHT.Add("Third", "!"); We can use key to find value like: myHT -> "Hello"...
1
by: diego | last post by:
Hi all, If I have a combo bound to as datasource, how can I search for a particular value. example i have the value 1,2,3,4 in col1 and A, B, C, D in col 2 of a datatablem and this datatable is...
3
by: squash | last post by:
I have spent two hours trying to make sense of this script, called crazy.php. The output should be nothing because $cookie_password is nowhere defined in this script, correct? But it actually...
4
by: Matt Kruse | last post by:
According to standards, if an option is selected and it has no VALUE attribute, the contents of the option tag is to be submitted. So: <select name="sel"> <option selected>Value</option>...
3
by: cmay | last post by:
I have a situation where I need a collection, where I can find the VALUE (e.g. customer name) by it's key (ID value), AND also find the ID value by the customer name. Is there anything that does...
11
by: TechnoAtif | last post by:
Here is the other one..This requires a textbox to open while clicking of a radiobutton in one part and in the other part on the click of a list/menu. I want that..as I click the second...
3
by: Friebo | last post by:
Hi, I'm having troubles with the following: I have 2 tables, Candidates and Attachments. In the Candidate there is a column called email1. In the Attachment table, there is a column called...
10
by: dkyadav80 | last post by:
<html> /// here what shoud be java script for: ->when script run then not display all input text field only display selection field. ->when user select other value for institute only this...
0
by: shapper | last post by:
Hello, I created the following SelectList: var targets = new Dictionary<string, string>(); targets.Add("New Window", "_blank"); targets.Add("SameWindow", "_self"); viewData.Targets = new...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.