0

我有两个像这样初始化的对象:

var series = new Dictionary<string,Dictionary<string,int>>()
{
   {"0", new Dictionary<string, int>() },
   {"1", new Dictionary<string, int>() },
   {"2", new Dictionary<string, int>() }
}

var periodValues = new Dictionary<string,int>();
{
   {"Jan", 0 },
   {"Feb", 0 },
   {"Mar", 0 }
}

然后我有另一个填充值的对象:

 var target = new Dictionary<string,Dictionary<string,int>>()
 {
       { "0", 
         new Dictionary<string, int>()
         {
            {"Jan", 12 },
            {"Mar", 22 }
         } 
       },
       { "1", 
         new Dictionary<string, int>()
         {
            {"Mar", 37 }
         } 
       },
       { "2", 
         new Dictionary<string, int>()
         {
            {"Jan", 4 },
            {"Feb", 48 },
            {"Mar", 22 }
         } 
       }
 }

series并且target总是相同的Key,而target[key].Keyskey类型string为 ) anykey可以是 的子集(最多相同)periodValues.Keys

现在我想series.Values根据中的键填写,periodValues.Keys但使用target[key].Value. 所以:

foreach (var numberValue in target.Keys)
{
    foreach (var period in target[numberValue].Keys)
    {
        periodValues[period] = target[numberValue][period];
    }
    series[numberValue] = periodValues;
}

但是我陷入了外部变量陷阱……这意味着 all series[key]for anyseries.Keys都等于 last periodValues。根据这篇文章,我尝试了许多解决方案来逃避外部变量陷阱,但没有运气。有人知道解决方案或更好的方法吗?

4

1 回答 1

0

periodValues如果有人感兴趣,我通过在第一个内部声明和初始化来解决问题foreach

foreach (var numberValue in target.Keys)
{
    var periodValues = new Dictionary<string,int>();
    {
       {"Jan", 0 },
       {"Feb", 0 },
       {"Mar", 0 }
    }
    foreach (var period in target[numberValue].Keys)
    {
        periodValues[period] = target[numberValue][period];
    }
    series[numberValue] = periodValues;
}
于 2012-12-14T09:50:38.463 回答