The 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”不在第二个查询的范围内,对吧?“父”范围变量仅在声明它的查询中才有意义。
您可以将这两个查询合并为一个查询,如下所示:
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;
同样,这里很清楚“父级”仅在“内部”查询的范围内,对吗?
但与第一种语法相比,这种语法很难阅读;为什么“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;
That's 与前两个版本完全相同。继续只是为了方便。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”不在第二个查询的范围内;它只是第一个查询的一部分。