2010-06-11 98 views
1

我有下面的代碼,我試圖通過我的qestAires匿名類型的孩子問題。當我到達foreach循環時,出現以下錯誤:不能使用匿名類型的foreach

foreach statement cannot operate on variables of type 'Question' because 'Question' does not contain a public definition for '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) 
     { 

     } 
+0

不'questAires'解析到什麼類型的?您可以在調試器中使用Intellisense/tooltip進行檢查,只需在LINQ語句後面斷開即可。 – ChrisF 2010-06-11 20:46:14

+1

聽起來像questAires.Questions沒有實現IEnumerable。 – 2010-06-11 20:48:03

回答

5

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() 
+0

完美,你是男人。 – 2010-06-11 20:58:24

0

q實際解決,從枚舉dc.Questions.Where(...)一個單一的項目,所以是的,你只會得到一個單一的項目 - 不是枚舉 - 的問題。