不能在匿名类型上使用foreach(Can't use foreach on a anonymous type)

编程入门 行业动态 更新时间:2024-10-24 21:27:09
能在匿名类型上使用foreach(Can't use foreach on a anonymous type)

我有下面的代码,我试图通过我的qestAires匿名类型的孩子问题。 当我到达foreach循环时,我得到错误:

foreach语句不能对“问题”类型的变量进行操作,因为“问题”不包含“GetEnumerator”的公共定义

我需要做些什么来解决这个问题呢?

var questAires = (from qs in dc.Questionnaires from q in dc.Questions.Where(t => t.QuestionnaireId == qs.QuestionnaireID) from r in dc.Responses.Where(qr => qr.QuestionID == q.QuestionId).DefaultIfEmpty() where qs.QuestionnaireID == QuestionnaireId select new { qs.Description, Questions = q, Responses = r }).Single(); foreach(var question in questAires.Questions) { }

I have the code below where I am trying to go through the child questions of my qestAires anonymous type. When I get to the foreach loop i get the error:

foreach statement cannot operate on variables of type 'Question' because 'Question' does not contain a public definition for 'GetEnumerator'

What do I need to do differently to get around this?

var questAires = (from qs in dc.Questionnaires from q in dc.Questions.Where(t => t.QuestionnaireId == qs.QuestionnaireID) from r in dc.Responses.Where(qr => qr.QuestionID == q.QuestionId).DefaultIfEmpty() where qs.QuestionnaireID == QuestionnaireId select new { qs.Description, Questions = q, Responses = r }).Single(); foreach(var question in questAires.Questions) { }

最满意答案

questAires.Questions只会解决一个问题,你会为每个问题得到一个questAires对象(这将导致.Single()抛出)。

我想你想要这样的东西:

var questAires = (from qs in dc.Questionnaires select new { qs.Description, Questions = from q in dc.Questions where q.QuestionnaireId == qs.QuestionnaireID select new { Question = q, Response = (from r in dc.Responses where r.QuestionID == q.QuestionId select r).DefaultIfEmpty() } }).Single()

questAires.Questions will only resolve to a single question, and you will get one questAires object for each question (which will cause .Single() to throw).

I guess you want something like this:

var questAires = (from qs in dc.Questionnaires select new { qs.Description, Questions = from q in dc.Questions where q.QuestionnaireId == qs.QuestionnaireID select new { Question = q, Response = (from r in dc.Responses where r.QuestionID == q.QuestionId select r).DefaultIfEmpty() } }).Single()

更多推荐

本文发布于:2023-07-26 03:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270709.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能在   类型   foreach   anonymous   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!