[英]Linq 'join … into' doesn't return joined objects
我是SQL和LINQ的新手。 我尝试了一个简单的代码,使用join...into
语法将两个列表join...into
,但是结果不是我所期望的。
public static void Main(string[] args)
{
IEnumerable<KeyValuePair<char,int>> list1 = new []{
new KeyValuePair<char,int>( 'a', 1) ,
new KeyValuePair<char,int>( 'b', 2) ,
new KeyValuePair<char,int>( 'c', 3) };
IEnumerable<KeyValuePair<char, int>> list2 = new[]{
new KeyValuePair<char,int>( 'b', 10) ,
new KeyValuePair<char,int>( 'c', 20) ,
new KeyValuePair<char,int>( 'd', 30) };
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key into joinTable
from t in joinTable
select new { element = t };
foreach (var el in joinQuery)
Console.WriteLine(el);
}
输出为:
{ element = [b, 10] }
{ element = [c, 20] }
我期望的是joinTable
包含联接的记录,例如:
{element = {[b, 2], [b, 10]}}
{element = {[c, 3], [c, 20]}}
您能解释一下... into joinTable
的部分实际上做了什么,为什么我可以在最后一次选择中使用x
而不能使用y
:
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key into joinTable
from t in joinTable
select new { element = t,
first = x, // OK
second = y} // Error: The name y doesn't exist in the current context
根据Jon Skeet的博客 , join ... into
语法将转换为GroupJoin()
,而不是您期望的Join
。
但是,您真正想要的是一个真正的联接,就像这样:
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key
select new { x, y };
在查询中,您无法访问y
因为join into
的语法不同。 您不需要from... joinTable
另一个from... joinTable
而必须直接访问joinTable
:
var joinQuery = from x in list1
join y in list2
on x.Key equals y.Key into joinTable
select new {joinTable.x, matches = joinTable.y.ToList()};
但这将导致y
具有list2
中的所有匹配元素。 那是Join
(每个匹配元素导致一个“行”)和GroupJoin
(匹配项分组在一起)之间的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.