Home > Enterprise >  How can change two 1d list array to 2 dimensional list array?
How can change two 1d list array to 2 dimensional list array?

Time:08-12

List<int> Boxsize = {3,1,6,7}

List<int> Boxunit = {2,7,4,9}

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

I try to make 2-dimensional list as like each element (Boxsize[i], Boxunit[i]) because Boxsize, Boxunit will variable

ex.

List<List<int>> Allbox = {{3,2} , {1,7} , {6,4} , {7,9}}

for (int i = 0; i < Boxsize.Count; i  )
{
    Allbox[i].Add(Boxunit[i]);
    Allbox[i].Add(Boxsize[i]);    
}

It doesn't work, and I am getting an ArgumentOutOfRangeException.

Would you help me this?

CodePudding user response:

You can simply initialize the nested list item inside the for.

var innerList = new List<int>();

innterList.Add(Boxunit[i]);
innterList.Add(Boxsize[i]);

Allbox.Add(innerList);

You could, though just use a Dictionary or a custom class.

CodePudding user response:

Using dictionary instead of list may be more useful.

List<int> Boxsize =new() { 3, 1, 6, 7 };
List<int> Boxunit =new() { 2, 7, 4, 9 };
Dictionary<int, int> s = new();
for (int i = 0; i < Boxsize.Count; i  )
{
    s.Add(Boxsize[i], Boxunit[i]);
}
  • Related