Linq 'join ... into' 不 return 连接对象

Linq 'join ... into' doesn't return joined objects

我是 SQL 和 LINQ 的新手。我尝试了一个使用 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 部分实际上做了什么吗,以及为什么我可以在最后 select 中使用 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

如果我没理解错的话,您基本上是在尝试从列表 1 和列表 2 中获取与键匹配的所有信息。如果是这样,您可以这样做:

var joinQuery = from x in list1
                join y in list2
                on x.Key equals y.Key
                select new
                {
                    first = x,
                    second = y
                };

您不需要将其添加到任意 table 中,只需 select 来自联接的结果。

根据 Jon Skeet's blogjoin ... 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 但必须直接访问 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(每个匹配元素一个 "row")和 GroupJoin(将匹配组合在一起)之间的区别。