Digilee
Digilee

Reputation: 35

Best way to handle array of arrays in C#

I need to create an array of string arrays in C#. Basically, I want to do the following, kind of a hybrid C/C#:

private string[] revA = new string[] {"one", "two", "three" };
private string[] revB = new string[] {"four", "five", "six" };
private string[] revC = new string[] {"seven", "eight", "nine" };

string[,] list = {revA, revB, revC};

string outStr = list[0][0];  // outStr == "one"
string outStr = list[2][1];  // outStr == "eight"

But I know that won't work.

I've looked into ArrayList and List, but I'm not sure how to make it work. Any help would be appreciated.

Upvotes: 1

Views: 257

Answers (4)

JonasH
JonasH

Reputation: 36361

While jagged and multidimensional arrays have been mentioned, a third option is a custom multidimensional array type. Something like

    public class My2DArray<T>
    {
        public T[] Array { get; }
        public int Width { get; }
        public int Height { get; }

        public My2DArray(int width, int height, params T[] initialItems)
        {
            Width = width;
            Height = height;
            Array = new T[width * height];
            initialItems.CopyTo(Array, 0);
        }
        public T this[int x, int y]
        {
            get => Array[y * Width + x];
            set => Array[y * Width + x] = value;
        }
    }

This has the advantage over multidimensional array in that the backing single dimensional array is directly accessible, and this can be good for interoperability, or if you just want to iterate over all items.

You can add constructors to initialize it however you want.

Upvotes: 0

MAG MS Programmer
MAG MS Programmer

Reputation: 1

This can be possible with ArrayList and with List in C#. I tried the following code you can check and explore more according to your requirements.

string[] reva = new string[] { "one", "two", "three" };
        string[] revb = new string[] { "four", "five", "six" };
        string[] revc = new string[] { "seven", "eight", "nine" };


        ArrayList arrayList = new ArrayList() { reva, revb, revc };

        List<string> nums = reva.Cast<string>().ToList();
        nums.ForEach(Console.WriteLine);
        Console.ReadLine();




        Console.ReadLine();

Upvotes: 0

tontonsevilla
tontonsevilla

Reputation: 2799

You need to use Jagged Array string[][] instead of Multidimensional Array string[,]

This source can give you more detail about it Why we have both jagged array and multidimensional array?

Upvotes: 3

Thomson Mixab
Thomson Mixab

Reputation: 657

string[,] list = new string[3, 3] {{"one", "two", "three" },
                                  {"four", "five", "six" },
                                  {"seven", "eight", "nine" } };



string outStr = list[0, 0];  // outStr == "one"

Upvotes: 1

Related Questions