If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Multidimensional SortedList (C#)

I am trying to create a 2-Dimensional SortedList in C#. I need to be able to look up a value using two keys, much like x,y coordinates.

See the table below. I need to be able to input two keys (A,C) and have the value '3' returned. The keys are an enumeration I have and the values will be integers. The standard C# SortedList only supports one key to one value. How can I best do this in C#?

If you want to go with the typesafe generics, you may think about
an invertible mapping from your 2-d parameter space to a 1-d parameter
space. Usually, there are two approaches for this:

1. (A,B) -> "A_B"

The function maps the two letters (A,B) to a string "A_B".
Your SortedList thus is of type SortedList(of string,integer).

2. (A,B) -> 5

The function maps the two corresponding numbers to an integer
using the function x*3+y:

(A,A) = 4
(A,B) = 5
(A,C) = 6
(B,A) = 7

Your SortedList thus is of type SortedList(of integer,integer).

If performance is an issue go with the latter (which does in principle
the same as a 2-d array).

If performance really is an issue you may think about using a
SortedList/SortedDictionary versus an unsorted Dictionary: if you
read more often than write, a SortedList/SortedDictionary is a good
choice, otherwise use the Dictionary.

...Alternatively, you certainly could work with multidimensional arrays as
proposed by dspeidel.

/edit:
I forgot: What you could do if performance is not an issue but
nice design: create a class MyKey implementing IComparable
on your custom class (storing the two keys (A,B)) such that you could use
a SortedList/SortedDictionary(Of MyKey, Integer)

Cheers

Last edited by sec_ware; November 5th, 2007 at 09:54 AM.

If the only tool you have is a hammer, you tend to see every problem as a nail.
(Abraham Maslow, Psychologist, 1908-70)