Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# for loop of two dimensional List

Tags:

c#

loops

list

List<List<double>> A = new List<List<double>>()
{
    new List<double>() { 1, 0, 0 },
    new List<double>() { 1, -1, 0 }
};

List<List<double>> Temm = new List<List<double>>();
for (int i = 0; i < A.Count; i++)
{
     for (int j = 0; j < A[i].Count; j++)
     {
         if (A[i][j] != 0) 
         {
             Temm[i][j] = A[i][j]; 
         }
         else 
         { 
             Temm[i][j] = Temm[i][j - 1]; }
         }
     }
}

There is something wrong with this double for loop, I think Temm[i][j] maybe illegal, so what's the correct way ? I also wanted to know how to declare the given size of the two dimensional List

List<List<double>> Temm = new List<List<double>>

say Z * Y?

like image 489
user6703592 Avatar asked Mar 11 '23 08:03

user6703592


1 Answers

You have 2 problems.

  1. When you first start looping over an inner loop you should initialize the loop in that place in the output collection.
  2. When you try to access [i][j] - to one that doesn't yet exist - which is everytime it will fail. Instead use the Insert method:

    List<List<double>> A = new List<List<double>>()
    {
        new List<double>() { 1, 0, 0 },
        new List<double>() { 1, -1, 0 }
    };    
    
    List<List<double>> Temm = new List<List<double>>(A.Count);
    for (int i = 0; i < A.Count; i++)
    {
        Temm.Insert(i,new List<double>());
        for (int j = 0; j < A[i].Count; j++)
        {
            if (A[i][j] != 0) { Temm[i].Insert(j,A[i][j]); }
            else { Temm[i].Insert(j,Temm[i][j - 1]); }
        }
    }
    

Because each time you insert to the end of the list I would prefer to use the Add:

List<List<double>> B = new List<List<double>>();
for (int i = 0; i < A.Count; i++)
{
    List<double> innerResult = new List<double>();
    for (int j = 0; j < A[i].Count; j++)
    {
        if (A[i][j] != 0)
        {
            innerResult.Add(A[i][j]);
        }
        else
        {
            innerResult.Add(innerResult[j - 1]);
        }
    }
    B.Add(innerResult);
}
like image 167
Gilad Green Avatar answered Mar 19 '23 10:03

Gilad Green