使用公共密钥将两个字典连接起来 [英] Join two dictionaries using a common key

查看:56
本文介绍了使用公共密钥将两个字典连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图基于一个公共的查找值将两个Dictionary集合结合在一起.

I am trying to join two Dictionary collections together based on a common lookup value.

var idList = new Dictionary<int, int>();
idList.Add(1, 1);
idList.Add(3, 3);
idList.Add(5, 5);

var lookupList = new Dictionary<int, int>();
lookupList.Add(1, 1000);
lookupList.Add(2, 1001);
lookupList.Add(3, 1002);
lookupList.Add(4, 1003);
lookupList.Add(5, 1004);
lookupList.Add(6, 1005);
lookupList.Add(7, 1006);

// Something like this:
var q = from id in idList.Keys
        join entry in lookupList on entry.Key equals id
        select entry.Value;

上面的Linq语句只是一个示例,不能编译.对于idList中的每个条目,根据匹配的Key从lookupList中提取值.

The Linq statement above is only an example and does not compile. For each entry in the idList, pull the value from the lookupList based on matching Keys.

结果应该是lookupList中的值列表(1000、1002、1004).

The result should be a list of Values from lookupList (1000, 1002, 1004).

使用Linq最简单的方法是什么?

What’s the easiest way to do this using Linq?

推荐答案

from id in idList.Keys
where lookupList.ContainsKey(id)
let value1 = idList[id]
let value2 = lookupList[id]
select new {id, value1, value2}


或更经典的


Or, more classically

from kvp1 in idList
join kvp2 in lookupList on kvp1.Key equals kvp2.Key
select new {key = kvp1.Key, value1 = kvp1.Value, value2 = kvp2.Value}


查询中的错误是作用域之一:


The mistake in your query is one of scoping:

from a in theAs
join b in theBs on (leftside) equals (rightside)

a在左侧区域中. b在右侧区域中.

a is in scope in the leftside area. b is in scope in the rightside area.

这篇关于使用公共密钥将两个字典连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆