【问题标题】:2D array of dictionaries - copying字典的二维数组 - 复制
【发布时间】:2012-04-06 17:48:25
【问题描述】:

让我们告诉我有一个二维字典数组:

public Dictionary<int, string>[,] mat = new Dictionary<int, string>[3, 5]
{
  { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() },
  { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() },
  { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() },
  { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() },           
  { new Dictionary<int, string>(), new Dictionary<int, string>(), new Dictionary<int, string>() }
}

我需要复制这个到另一个。我尝试了所有方法。
比如:

matNew = mat;

但是当我更改第一个时,它仍然会自动更改第二个。
我真的不知道该怎么做。

【问题讨论】:

  • 一个改变,另一个改变,所以你是说你想要一个深拷贝?
  • 数组是引用类型; “mat”只是对实例的引用,“matNew = mat”复制引用,而不是实际的数组。您是要创建数组的副本,还是创建数组的副本以及其中的所有字典?
  • 我假设尺寸应该是[5, 3],而不是[3, 5]

标签: c# arrays dictionary copy


【解决方案1】:

我假设你想要一个深拷贝?

var matNew = new Dictionary<int, string>[mat.GetLength(0), mat.GetLength(1)];
for (int i = 0; i < mat.GetLength(0); ++i)
    for (int j = 0; j < mat.GetLength(1); ++j)
        matNew[i, j] = new Dictionary<int, string>(mat[i, j]);

Dictionary(IDictionary&lt;TKey, TValue&gt;) 构造函数复制指定字典中的所有元素,这可能是对现有字典执行浅层克隆的最快方法。这适合您的情况,因为您的键和值都是不可变的(intstring)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多