简体   繁体   English

加入Linq

[英]joining in Linq

When i declare 当我宣布

 int[] a = { 1, 2 ,10,30};

 int[] b = { 10, 20, 30 };

  var q = from item1 in a
                     join item2 in b
                     on item1 equals item2
                     into g
                     select g

1)What is actually getting selected into g ? 1)实际上被选入g的是什么? It is difficult to understand the into keyword. 这是很难理解into关键词。 if you give example to explain the keyword "into" ,i will be pleased. 如果您举例说明关键字"into" ,我将很高兴。

2) 2)

 How do the following code actually projected ?

1    from a in db.coll1
2    join b in db.coll2 on a.PK equals b.PK into b_join
3    from b in b_join.DefaultIfEmpty()
4    where
5      b.PK == null 
6   select new {
7      a.PK,
8      a.Value,
9      Column1 = (System.Int32?)b.PK,
10      Column2 = b.Value
    }

in line 2 we are using "b' to select the item in line 3 also we are using the same b ,does it mean we are overriding the data we selected at line 2 ? 在第2行中,我们使用“ b”来选择第3行中的项目,同时我们也使用相同的b,这是否意味着我们将覆盖在第2行中选择的数据?

1) You are doing a group join . 1)您正在进行群组加入 g will be an IGrouping for each element in a . g将是一个IGrouping在每个元件a g.Key will be the element from a , and g (which implements IEnumerable ) will contain all of the matching elements from b . g.Key将从元件a ,和g (它实现IEnumerable )将包含所有从匹配元件b To understand this fully, try it out in LINQPad . 要完全理解这一点,请在LINQPad中进行尝试。 Also, read the documentation . 另外,请阅读文档

2) The into keyword merges the first b into b_join , which will be an IGrouping as I described above. 2) into关键字将第一个b合并到b_join ,这将是如上所述的IGrouping After that, the first b is no longer in scope. 此后,第一个b不再在范围内。

If you use .NET Reflector on your compiled code, you can see that your first query is equivalent to the following: 如果在已编译的代码上使用.NET Reflector,则可以看到您的第一个查询等效于以下内容:

IEnumerable<IEnumerable<int>> q = a.GroupJoin(b,
   item1 => item1,
   item2 => item2,
   (item1, group) => group);

Note that you are performing a group join, but only returning the groups. 请注意,您正在执行组加入,但仅返回组。 Compare this with an ordinary join: 将此与普通联接进行比较:

IEnumerable<int> q = a.Join(b,
    item1 => item1,
    item2 => item2,
    (item1, item2) => item2);

This returns the elements in b that matches to each a, if any such element exists. 如果存在任何这样的元素,则返回b中与每个a匹配的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM