代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

使用LINQ合并C中的字典

c#
  •  2
  • Thorin Oakenshield  · 技术社区  · 14 年前

    我有三个听写

    Dictionary<int,List<string>> D1 = new Dictionary<int,List<string>>(); 
    Dictionary<int,List<string>> D2= new Dictionary<int,List<string>>(); 
    Dictionary<int,List<string>> D3 new Dictionary<int,List<string>>(); 
    
    
    D1[1] = new List<string>{"a","b"}; 
    D1[2] = new List<string>{"c","d"}; 
    D1[3] = new List<string>{"e","f"}; 
    D1[4] = new List<string>{"h"}; 
    
    D2[1] = new List<string>{"a","b"}; 
    D2[2] = new List<string>{"c","d"}; 
    D2[3] = new List<string>{"e","f"}; 
    D2[4] = new List<string>{"g"}; 
    D2[5] = new List<string>{"b","h"}; 
    D2[6] = new List<string>{"f","l"}; 
    D2[7] = new List<string>{"z"}; 
    

    我需要把两个听写合并成一个听写

    喜欢

    D3[1] = {"a","b","h"} 
    D3[2] = {"c","d"} 
    D3[3] = {"e","f","l"} 
    

    合并规则:

    d1[1]=“a”、“b”此列表将与d2中的值进行比较

    D2〔1〕={“A”、“B”}

    D2〔5〕={“B”、“H”}

    因此,上述三项将合并为

    d3[1]=“a”、“b”、“h”

    有什么办法用LINQ来做这个吗

    2 回复  |  直到 14 年前
        1
  •  2
  •   Jaroslav Jandek    14 年前

    但是,如果要合并这些值,您可能需要使用以下选项之一:

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

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

    编辑 -连接合并Linq样式的一种外观不好看的方法:

    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();
    }
    

    代码将列表保存在D2中,修改代码将很容易从D2中删除匹配的列表。

        2
  •  2
  •   Ivan G.    14 年前

    像这样(可能需要优化)?

         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)))));