c# - 连接两个字典

标签 c# linq

嗨,我有两个词典,我需要找到一种将它们结合在一起的方法。这是两种词典类型。

IDictionary<string, byte[]> dictionary1
IDictionary<IFileShareDocument, string> dictionary2


在这两个字典中,我必须创建第三个字典,如下所示

IDictionary<IFileShareDocument, byte[]> dictionary3


这两个字典的项目数完全相同,并且它们的string属性都是链接点。

我想要的是能够写点东西来做这样的事情:

dictionary1.value join with dictionary2.key
where dictionary1.key == dictionary2.value

This statement should result in dictionary3.


有什么办法可以实现我的目标,而我似乎找不到办法?

最佳答案

这是使用使用LINQ查询语法的一种方法(此方法与@KingKing的解决方案大致相同):

IDictionary<IFileShareDocument, byte[]> dictionary3 =
    (from item1 in dictionary1
     join item2 in dictionary2 on item1.Key equals item2.Value
     select new { item2.Key, item1.Value })
         .ToDictionary(x => x.Key, x => x.Value);


请注意,对于使用joinfrom的示例,上面的方法非常有用,因为它效率更高。我之所以将其包含在此处,是因为如果您像我一样(对SQL更为熟悉,它将自动将类似的内容转换为联接),那么这种糟糕的方法可能是第一个想到的方法:

IDictionary<IFileShareDocument, byte[]> dictionary3 =
    (from item1 in dictionary1
     from item2 in dictionary2
     where item1.Key == item2.Value
     select new { item2.Key, item1.Value })
         .ToDictionary(x => x.Key, x => x.Value);

关于c# - 连接两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18490328/

相关文章:

c# - 在不修改注册表项的情况下读取 Excel InterMixed DataType

c# - AuthorizationFilterAttribute 的 OnAuthorization 方法会在每次请求到达时执行吗?

c# - 封装LINQ GroupBy Select

c# - LINQ to Entities 消息中仅支持无参数构造函数和初始值设定项

vb.net - 动态 LINQ。 'FieldName' 类型中不存在属性或字段 'ClassName'

javascript - 使用 WebDriver 扩展 JavaScript 菜单

c# - 如何从 <form> 标签中获取值?

c# - 从 C# 中的枚举中获取 int 值

c# - 如何将两个列表的项目与 linq 进行比较?

c# - LINQ - GroupBy 一个键,然后将每个分组的项目放入单独的 'buckets'