【问题标题】:How to copy 2D arraylist to another如何将二维数组列表复制到另一个
【发布时间】:2014-10-06 05:26:14
【问题描述】:

你能告诉我如何在不引用同一个数组实例的情况下将二维数组列表复制到另一个吗?

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]);
            }
    }
}

【问题讨论】:

  • 最坏的情况,你可以遍历 class_lables 并将项目添加到 labels1

标签: c# arrays arraylist


【解决方案1】:
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();
}

【讨论】:

  • @DP。好的。我编辑了答案。希望它能解决问题。否则请告诉我您在哪一行遇到错误。
  • 感谢您的更新。错误仍在同一个地方发生:Console.Write(lables1[x][y]+" ");。错误说,Index was out of range. Must be non-negative and less than the size of the collection.
  • @DP。始终使用foreach 而不是for 循环来防止此类错误。那么除此之外,它有用吗?
  • 是的。非常感谢您提供的所有帮助并抽出宝贵时间。
猜你喜欢
  • 2021-12-31
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多