对于某些实时数据表示,我使用两个必须合并的词典:
//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>>>>();
合并这两个词典最好的是什么?
在这种情况下,我确信有一些重复
答案 0 :(得分: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;
}
}
}
}
}