Daniel
Daniel

Reputation: 3

Collection requiring two keys to a unique value

I was wondering if anyone knew a good way to store data such that it would be indexed with two keys. Basically, I need something like a table (top-row is key1, left-column is key2, letters are values returned from indexing):

[ ] [1] [2] [3] [4]
[1] [A] [B] [C] [D]
[2] [B] [E] [F] [G]
[3] [C] [F] [H] [I]
[4] [D] [G] [I] [J]

I could easily implement this as a multidimensional array, but since half the table is always identical, it seemed redundant. So far, the best solution I can come up with involves a 2 Dimensional list, with the second dimension being a variable length, while forcing either the larger or the smaller of the two keys to be indexed first. This turns the table into:

[ ] [1] [2] [3] [4]
[1] [A]
[2] [B] [E]
[3] [C] [F] [H]
[4] [D] [G] [I] [J]

Does anyone have any better ideas?

Edit: I may have figured out a solution on my own. See comments.

Upvotes: 0

Views: 1033

Answers (2)

myermian
myermian

Reputation: 32515

If you're running .NET 4 you should look at the Tuple class.

IDictionary<Tuple<K1, K2>, V> - This is the proper way to represent a 2-key dictionary.

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 456507

I recommend:

Dictionary<Tuple<int, int>, char>

unless your table will be very large.

Upvotes: 1

Related Questions