-1

I am trying to convert a List<T> to a Jagged Array T [][]. But each array inside the Jagged Array is repeating the first N Elements of the List. I know that my code is doing exactly that, but how can I iterate over my list in a different way so I dont go through the same N elements?

Please ignore the DataTree<T> type, its just a reference data structure topology to create the Jagged Array.

  public static T[][] ToJaggedArrray<T>(this List<T> data, DataTree<T> dataTree)
        {
            // Get total elements on each row
            //dataTree.DataCount = total elements in data structure
            int totalElementsPerArray = dataTree.DataCount / dataTree.BranchCount;

            // dataTree.BranchCount = number of elemets/rows
            int numElements = dataTree.BranchCount;



            T[][] outPut = new T[numElements][];

            for (int i = 0; i < outPut.Length; i++)
            {
                T[] temp = new T[totalElementsPerArray];

                for (int j = 0; j < temp.Length; j++)
                {
                    temp[j] = data[j];

                }

                outPut[i] = temp;
            }

            return outPut;
        }

/* Output:

54
19
83
80
28
48
46
16
52
38
41
10

Element(0): 54 19 83 80
Element(1): 54 19 83 80
Element(2): 54 19 83 80

*/


/* Expected Output:

54
19
83
80
28
48
46
16
52
38
41
10

Element(0): 54 19 83 80
Element(1): 28 48 46 16
Element(2): 52 38 41 10

*/
  • 2
    I can't ignore that `DataTree` . – Henk Holterman Jul 07 '19 at 21:59
  • Take a look at [this answer](https://stackoverflow.com/a/419058) to [Split List into Sublists with LINQ](https://stackoverflow.com/q/419019/3744182). It should do what you want, then package the returned results into your required jagged array using `.ToArray()`. – dbc Jul 07 '19 at 22:26
  • The problem in your code is that the expression `temp[j] = data[j];` is going to copy the same, first `totalElementsPerArray` elements of `data` into each new sub-array `temp`. You would want to take into account the elements already copied, e.g. by keeping a counter or computing a new offset into `data` for each subsequent destination array. That said, "chunking" a list (or array) like this is a well-known problem, and there many solutions available on SO already. See marked duplicates. – Peter Duniho Jul 08 '19 at 00:11

1 Answers1

-2

I believe that your problem is that you do not understand loops. In your case, that nested for loop will always start at 0 and will always get exactly temp.length elements from data.

Do you see my point here?

golobitch
  • 1,303
  • 3
  • 17
  • 36
  • Yeah, I know that is exactly what is happening, that why I am asking the question – Nicholas Rawitscher Jul 07 '19 at 22:10
  • You are always getting the same for elements. Please try with temp[j] = data[j+ temp.Length*i); and watch out for any index that is out of bounds. Enclose this with try catch statement – golobitch Jul 07 '19 at 22:20