代码之家  ›  专栏  ›  技术社区  ›  Abe Miessler

不能对匿名类型使用foreach

  •  1
  • Abe Miessler  · 技术社区  · 14 年前

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

    foreach语句不能在上操作 “question”类型的变量,因为 “问题”不包含公共 “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)
            {
    
            }
    
    2 回复  |  直到 14 年前
        1
  •  5
  •   erikkallen    14 年前

    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()
    
        2
  •  0
  •   GalacticCowboy    14 年前

    q实际上从可枚举项解析为单个项 dc.Questions.Where(...) 所以,是的,你只会得到一个单一的项目-不是一个可枚举的-为问题。