Merging Dictonaries in C# using LINQ

前端 未结 2 1204
闹比i
闹比i 2021-01-15 03:36

i\'ve three Dictonaries like

Dictionary> D1 = new Dictionary>(); 
Dictionary

        
相关标签:
2条回答
  • 2021-01-15 03:55

    Something like this (maybe needs optimisation)?

         var lr =
        (from gr in
            (from pair in D1.Union(D2).Union(D3)
             group pair by pair.Key)
         select new KeyValuePair<int, IEnumerable<List<string>>>(gr.Key, gr.Select(x => x.Value))
        ).ToDictionary(k => k.Key, v => v.Value.Aggregate((t, s) => (new List<string>(t.Union(s)))));
    
    0 讨论(0)
  • 2021-01-15 03:57

    However are you trying to merge the values, you will probably want to use one of these options:

    D3[1] = D1[1].Union(D2[1]);
    

    or

    D3[1] = D1[1].Concat(D2[1]);
    

    Edit - an ugly-looking method for joined merges Linq-style:

    foreach (var kvp in D1)
    {
        D3[kvp.Key] =
            (from string letter in kvp.Value
            select
                (from IEnumerable<string> list in D2.Values
                where list.Contains(letter)
                select list)
                 // Union all the D2 lists containing a letter from D1.
                .Aggregate((aggregated, next) => aggregated.Union(next)))
            // Union all the D2 lists containing all the letter from D1.
            .Aggregate((aggregated, next) => aggregated.Union(next))
            // Convert the unioned letters to a List.
            .ToList();
    }
    

    The code keeps the lists in D2, it would be pretty easy to modify the code to remove the matched lists from D2.

    0 讨论(0)
提交回复
热议问题