Home > Enterprise >  C# Merging dictionaries inside of an object
C# Merging dictionaries inside of an object

Time:10-12

I realize there are tons of posts on this subject but I still haven't found what I am looking for reading the answers.

I get two objects A and B, that both have a dictionary and a set of booleans. Dictionaries are shaped the same, just the data differs. My end goal here is to create a 3rd object C, copy of A with its dictionary updated to have values from A and B according to a set of rules (for instance C.dictionary would have all A.dictionary.[x] if A.Dictionary.[x].Value.days < 5 and and all B.dictionary.[x] if days > 5). If you have a solution for this that would be awesome, otherwise, here is where I am at and where I fail:

I am trying to create a new dictionary and and loop through A and B to add the values... I'll add the rules after. Once I will have it I'll find a way to place this dictionary into object C. (tell me if over engineered, I am very new to C#).

var dict = new Dictionary<DateTime, TypeData>();
foreach (var item in A.dictionary.keys)
   {
      dict.Add(A.Dictionary[item]);
   }

This does not work for 2 reasons:

  • item does represents A.dictionary[x].key not A.dictionary[x] (also contains value and non public members)
  • "Add" gets underlines and does not show more info for the error

Thanks a lot for checking my post !

CodePudding user response:

try this

var dictionariesToCombine = new Dictionary<DateTime, TypeData>[] {dictA,dictB};

Dictionary<int, int> dictC = new Dictionary<DateTime, TypeData>();

    for (var i=0; i< dictionariesToCombine.Length; i  )
    {
        foreach (var item in dictionariesToCombine[i])
        {
            if( 
                  (i==0 and your conditions)
                 || (i==1 and your conditions)
               )
            resultDict.Add(item.Key, item.Value);
        }
    }
    
  • Related