November 4th, 2007, 05:26 PM
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#?
public enum letters
A B C
A 1 2 3
B 2 3 1
C 3 1 2
Last edited by AxessTerminated; November 4th, 2007 at 08:53 PM.
Geek isn't just a four-letter word; it's a six-figure income.
November 5th, 2007, 01:55 AM
coming from a c world I would think a two dimensional array like int array ; You can use this directly array[A][C] bur I am not sure if that works for c#.
If you spend more on coffee than on IT security, you will be hacked. What\'s more, you deserve to be hacked.
-- former White House cybersecurity adviser Richard Clarke
November 5th, 2007, 08:42 AM
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.
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)
Last edited by sec_ware; November 5th, 2007 at 08: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)
November 18th, 2007, 06:30 PM
In Java it's just as follows. I don't know if there is a .length method/function in C# though!
Then you could just tranverse the array with a nested loop to either look up a value or fill the array.
int arrayName = new int;
(for int i=0; i < arrayName.length; i++)
for(int j = 0; j < arrayName[i].length; j++)
// do whatever
By shred2er in forum Programming Security
Last Post: September 29th, 2003, 02:25 AM