0

对于一些实时数据表示,我使用了两个必须合并的字典:

 //Orderdata string,orderdetails int,day int,hour int,count
 var OldData = new Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>>();
 var TodayData = new Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>>();

合并这两个字典的最佳方法是什么?

在这种情况下,我确定有一些重复

4

1 回答 1

1

这样的事情将合并每个级别的字典。不过,您需要清楚您想要在“叶”级别执行的操作,因为在这种情况下,通过所有嵌套字典具有相同复合键的值只会从 oldData 替换为 todayData。

private void MergeDictionaries()
{
    var oldData = new Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>>();
    var todayData = new Dictionary<string, Dictionary<int, Dictionary<int, Dictionary<int, int>>>>();

    foreach (var kvp in oldData)
    {
        Dictionary<int, Dictionary<int, Dictionary<int, int>>> today;
        if (!todayData.TryGetValue(kvp.Key, out today))
        {
            today = new Dictionary<int, Dictionary<int, Dictionary<int, int>>>();
            todayData.Add(kvp.Key, today);
        }

        foreach (var kvp2 in kvp.Value)
        {
            Dictionary<int, Dictionary<int, int>> today2;
            if (!today.TryGetValue(kvp2.Key, out today2))
            {
                today2 = new Dictionary<int, Dictionary<int, int>>();
                today.Add(kvp2.Key, today2);
            }

            foreach (var kvp3 in kvp2.Value)
            {
                Dictionary<int, int> today3;
                if (!today2.TryGetValue(kvp3.Key, out today3))
                {
                    today3 = new Dictionary<int, int>();
                    today2.Add(kvp3.Key, today3);
                }

                foreach (KeyValuePair<int, int> kvp4 in kvp3.Value)
                {
                    // What you do here determines what happens when there are key duplicates
                    today3[kvp4.Key] = kvp4.Value;
                }
            }
        }
    }
}
于 2013-09-27T16:36:06.247 回答