c# - 使用 LINQ 在 C# 中合并字典

标签 c#

我有三个字典,例如

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 来做到这一点

最佳答案

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

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 中删除匹配列表将非常容易。

关于c# - 使用 LINQ 在 C# 中合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3156456/

相关文章:

c# - 我如何在 C# 中使用 XNA 来减少碰撞时的生命周期?

c# - 未找到请求的服务

c# - 使用 null : casting vs default 调用重载

c# - 我应该使用动态关键字来优化转化吗?

C# Linq to Sql XML 检索父级中最近的元素

c# - wpf 以编程方式设置排序,以便将标题切换为已排序

c# - WinForm ZIndex 到桌面

c# - 如何在异步方法中实现 InvokeRequired UI 模式?

c# - 关于 ASP.net 中数据源对象的问题

c# - WCF错误类型识别