0

I am trying to create 2-dimensional array of ints with two columns, but an unknown amount of rows. I know that in order to create the 2D array itself I do the following:

List<List<int>> myList = new List<List<int>>();

But how do I modify this to specify the number of columns? And how would I add a row to this array?

3
  • 1
    It is hard to understand your problem. Can you show us some examples of data you are planning to store here? Can the number of columns change or is it fixed once set? Can the number of rows change or is it fixed once set? Can column 1 have a different number of rows than column 2? Commented Jun 11, 2017 at 23:35
  • 1
    here is a good question/answer u should look at stackoverflow.com/a/6723318/6328256 Commented Jun 11, 2017 at 23:35
  • Use the List like you got it. If you only use to columns then just use two. There is no need to explicitly set two. It works correctly if you just move on to the next list after adding two elements to the current list. Commented Jun 11, 2017 at 23:57

4 Answers 4

2

You could use a List of int arrays. The List would represent the rows, and each int array in the List would be one row. The length of each array would equal the amount of columns.

     List<int[]> rows = new List<int[]>();
        int[] row = new int[2];
        row[0] = 100;
        row[1] = 200;
        rows.Add(row);

As long as each int array is length two (int[] row = new int[2]), all rows will have two columns. The List can have any number of int arrays added to it in this way.

Sign up to request clarification or add additional context in comments.

Comments

2

There is no way to create 2D array (or any other sort of array) with unknown number of elements. Once you initialize it you have to provide number of elements.

The syntax for multidimensional array is the following:

var arr = new int[k, l, n,...]

You can create so called jagged array, i.e. array of arrays and initialize it in the cycle. You will still need to initialize it with a number of subarrays and then fill with those subarrays of given lengths:

var arr = new int[][n];
for (int i = 0; i < arr.Length; i++)
{
    arr[i] = new int[subArrayLength];
}

What you actually do is List of Lists which can have any number of "rows" of any length. You can add new list of specific length to an outer list by List method Add() and the same way you can add an element to any of inner List.

So basically to add a "row" you would need the following:

List<List<int>> table = new List<List<int>>();
table.Add(Enumerable.Repeat(defaultValue, numberOfColumns).ToList());

To add a column you would need something like this:

foreach (var row in table)
{
    row.Add(defaultValue);
}

It seems that you want to simulate table structure - for that I would suggest to create a class to incapsulate table logic from above inside so that any addition of row will cause addition of outer List of current numberOfColumns size and addition of column will cause addition of an element to all outer lists.

However if you need a fixed number of columns the best alternative you can use is to declare a new class with your columns mapped to the properties of the class and then simply declare a List like it is described in the following answer as @shash678 pointed

1 Comment

new List<int>(numberOfColumns) does not initialize a "new list of specific length". This is not the case, as List.Count would still be zero, as there are no elements (columns) in the list...
1

Original answer: Consider using a List<Tuple<int, int>>.

Explanation: To begin with, an int[] is not a List<>. From the spirit of your question you seem to have the need to group several units of data together with a finite size, like a records in a table. You could decide to create a POCO with a more descriptive name (which would increase code readability and help with semantics), use an array of fixed size, or use a Tuple. Since there is no mention as to the need for mutability, and the size of the inner "array" will be fixed, I would suggest a Tuple. Through type safety you will ensure that the size and shape of each new object added to the list of Tuples is correct.

Your fist and second questions would be taken care, as far as the 3rd, see: Tuple Pair

e.g. list.Add(Tuple.Create<int,int>(1,1));

2 Comments

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
I appreciate your opinion Marco. This is indeed one possible answer to the asker's question. If my answer is not chosen then so be it. The concept of columns and rows is arbitrary in this case. The asker makes no mention as to the necessity for mutability. Only that data will be stored in an object of particular size.
0

I feel like these answers are leading you down a bad path. When learning how to program, you should also consider best practices. In this case your code is what you should use. If you can avoid setting explicit array size, you should(In my opinion). List were create for this purpose. This sample app explains how to use the list correctly in this scenario. My personal opinion is to avoid using arrays if you can.

        int someNumberOfRow = 10;//This is just for testing purposes.
        Random random = new Random();//This is just for testing purposes.

        List<List<int>> myList = new List<List<int>>();


        //add two elements to the an arraylist<int> then add this arraylist to myList arraylist
        for(int i = 0; i < someNumberOfRow; i++)
        {
            //Create inner list and add two ints to it.
            List<int> innerList = new List<int>();
            innerList.Add(random.Next());
            innerList.Add(random.Next());

            //Add the inner list to myList;
            myList.Add(innerList);
        }


        //This prints myList
        for(int i = 0; i < myList.Count; i++)
        {
            Console.WriteLine((i + 1) + ": " + myList[i][0] + " - " + myList[i][1]);
        }

        Console.WriteLine("\n\n");

        //If the app may scale in the future, I suggest you use an approach similar to this
        foreach(List<int> sublist in myList)
        {
            foreach(int columns in sublist)
            {
                Console.Write(columns + " ");
            }
            Console.WriteLine();
        }
        Console.ReadLine();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.