D P.
D P.

Reputation: 1079

How to copy 2D arraylist to another

Can you please tell me how can I copy a 2 dimensional array-list to another without referring to the same array instance?

void partial_entropy(List<List<String>> class_lables)//This 2D "class_lables" arraylist contains many elements
{
    List<List<String>> lables1 = new List<List<String>>();
    lables1 = class_lables; //copying old arraylist to new array list called "lables1"
    //if I copy using the above method, both refer to same array instance.

    //Therefore, I would like to use something like "CopyTo" method
    class_lables.CopyTo(lables1, 0);//This did not work

    for (int x = 0; x < lables1.Count; x++)//To print out the newly copyed 2D array
    {
            for (int y = 0; y < 1; y++)
            {
                    Console.Write(lables1[x][y]+" ");
                    Console.WriteLine(lables1[x][y+1]);
            }
    }
}

Upvotes: 0

Views: 587

Answers (1)

Ghasem
Ghasem

Reputation: 15643

List<string> tempList=new List<string>();
foreach (List<String> lst in class_lables)
{
    foreach (string str in lst)
            tempList.Add(str);
    lables1.Add(tempList);
    tempList.Clear();
}

Upvotes: 1

Related Questions