into
子句是一个查询续延子句。查询续延会从作用域中删除所有先前的范围变量,然后引入新的范围变量。
这可能不是非常清晰。让我举个例子来更好地说明它。
我有棕色的眼睛;我妹妹有蓝色的眼睛。假设我们想找到像我一样的人:拥有蓝眼睛兄弟姐妹的棕眼睛人。我们可以这样做:
var parentsWithABlueEyedChild =
from parent in parents
where parent.Children.Any(c=>c.EyeColor == Blue)
select parent;
var brownEyedChildren =
from parentWithABlueEyedChild in parentsWithABlueEyedChild
from child in parentWithABlueEyedChild.Children
where child.EyeColor == Brown
select child;
好的,你有两个查询。第二个查询操作的是第一个查询的结果。现在,你认为“parent”在第二个查询中不在范围内,对吗?“parent”区域变量只有在声明它的查询中才有意义。
你可以将这两个查询合并成一个查询,如下所示:
var brownEyedChildren =
from parentWithABlueEyedChild in (
from parent in parents
where parent.Children.Any(c=>c.EyeColor == Blue)
select parent)
from child in parentWithABlueEyedChild.Children
where child.EyeColor == Brown
select child;
看起来,"parent" 只在 "inner" 查询中有效,对吗?
但是与第一种语法相比,这种语法难以阅读;为什么要在使用三行之前引入 "parentWithABlueEyedChild"?第一种版本更清晰。我们可以使用查询延续将其转换为一个查询,同时保持第一种版本的可读性:
var brownEyedChildren =
from parent in parents
where parent.Children.Any(c=>c.EyeColor == Blue)
select parent into parentWithABlueEyedChild
from child in parentWithABlueEyedChild.Children
where child.EyeColor == Brown
select child;
这与前两个版本完全相同。继续语句只是一种方便的写法。parent
在继续子句中不在作用域内,因为如果将它们作为两个查询编写,它也不会在作用域内。
现在你明白了吗,为什么你的续集中 "con" 不在作用域内吗?
var q =
from con in contributions
group con by con.Response
into gResponse
select new
{
grop = gResponse.Count(),
con.ActivityID
};
完全相同
var gResponses =
from con in contributions
group con by con.Response;
var q =
from gResponse in gResponses
select new
{
grop = gResponse.Count(),
con.ActivityID
};
"con" 在第二个查询中不在作用域内,它只是第一个查询的一部分。