AustinT
AustinT

Reputation: 2026

Multidimensional data structure?

I need a multidimensional data structure with a row and a column.

EDIT
I want to be able to insert like this.

    static void Main(string[] args)
    {
        Program p = new Program();
        List<List<string()>> list = new List<List<string>()>();
        list.Insert("RAWR", 1, 2); // RAWR is the element to insert, 1 is the row, 2 is the col.
        list.Insert("Hello", 3, 5);
        for (int i = 0; i < list.Count; i++)
        {
            Console.WriteLine(list[i]);
        }
        Console.ReadKey();
    }

And of course this does not work, because the list does not support this functionality. I understand this code is bad, but I just want to get across what I am trying to accomplish.

So in a sense I will have a user who will choose which ROW and COL to insert the element to.

Upvotes: 1

Views: 1622

Answers (3)

Aamir
Aamir

Reputation: 5440

Perhaps a Dictionary might work with a Tuple as it's key:

Dictionary<Tuple<int, int>, string> dict = new Dictionary<Tuple<int, int>, string>();
dict.Add(new Tuple<int, int>(1, 5), "A");

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

I think a list of lists should work fine:

IList<IList<T>> multiDim = new List<IList<T>>();

You can insert new rows like this:

multiDim.Insert(atRow, new List<T>());

or insert a new element in a specific row:

multiDim[row].Insert(atColumn, myElement);

Note that you need to have enough elements in your list in order to call an Insert; otherwise, you will get an out-of-range exception. The easiest way to address this is to write a small utility method that adds empty items until the insertion is possible:

private static Expand<T>(IList<T> list, int index) {
    while (list.Count < index) {
        list.Add(default(T));
    }
}

Rewrite your program as follows:

Expand(list, 1);
list.Insert(1, "HELLO");
Expand(list, 5);
list.Insert(5, "RAWR");

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

SortedDictionary<int, T> seem to fit perfectly if your keys are integers or anything ordered like strings. Just put items by key to the dictionary.

var sparseArray = new SortedDictionary<int, string>();
sparseArray.Add(1, "notepad.exe");
sparseArray.Add(5, "paint.exe");
sparseArray.Add(3, "paint.exe");
sparseArray.Add(2, "wordpad.exe");

Upvotes: 0

Related Questions