我正在尝试使用LINQ创建一个group by语句.我收到错误当前上下文中不存在名称'con'.
在select之后的代码中,我试图获取ActivityID值,但列表'con'不可用.
List<Contribution> contributions =
contLogic.GetAllContibutionsByActivityIDToList(ActivityID);
var groups = from con in contributions
group con by con.Response
into gResponse
select new
{
grop = gResponse.Count(),
con.ActivityID
};
Run Code Online (Sandbox Code Playgroud)
我看过微软的样本,我不知道我做错了什么.
微软示例:
List<Product> products = GetProductList();
var orderGroups = from prod in products
group prod by prod.Category into prodGroup
select new { Category = prodGroup.Key, Products = prodGroup };
ObjectDumper.Write(orderGroups, 1);
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 19
该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;
Run Code Online (Sandbox Code Playgroud)
好的,你有两个问题.第二个查询对第一个查询的结果进行操作.现在,您同意"父"不在第二个查询的范围内,对吧?"父"范围变量仅在声明它的查询中具有含义.
您可以将这两个查询组合成一个查询,如下所示:
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;
Run Code Online (Sandbox Code Playgroud)
同样,这里很明显"父"只在"内部"查询的范围内,对吧?
但与第一种语法相比,这种语法难以阅读; 为什么"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;
Run Code Online (Sandbox Code Playgroud)
这与前两个版本完全相同.延续只是一种便利. parent不在continuation子句的范围内,因为如果将它们作为两个查询写出来,它就不在范围内.
现在是否清楚为什么"con"不在你的延续范围内?您的查询
var q =
from con in contributions
group con by con.Response
into gResponse
select new
{
grop = gResponse.Count(),
con.ActivityID
};
Run Code Online (Sandbox Code Playgroud)
与...完全相同
var gResponses =
from con in contributions
group con by con.Response;
var q =
from gResponse in gResponses
select new
{
grop = gResponse.Count(),
con.ActivityID
};
Run Code Online (Sandbox Code Playgroud)
"con"不在第二个查询的范围内; 它只是第一个查询的一部分.
Ant*_*ram 10
con不属于您的分组范围.请注意,在Microsoft示例中,它们的原始查询元素是prod,但在分组之后,它们引用了prodGroup.
您的查询是根据共同点将元素分组在一起Response,您基本上是"失去"个体con以获得更大的整体.您可能需要扩展分组以包含比响应更多的条件,例如
group by new { con.Response, con.ActivityID }
Run Code Online (Sandbox Code Playgroud)
然后通过ID参考ID
gResponse.Key.ActivityID
Run Code Online (Sandbox Code Playgroud)
或者也许可以访问每个组中第一个元素的ActivityID
gResponse.First().ActivityID
Run Code Online (Sandbox Code Playgroud)
如果没有关于您要完成什么的更多信息,我无法就您需要如何继续提供具体建议.