2012-11-21 74 views
0

我試圖從LINQ查詢返回IEnumerable<string>,我得到的錯誤: 無法轉換IEnumerable<AnonymousType>IEnumerable<string>從Linq查詢返回的IEnumerable <string>

我不知道如何去解決這個問題。

private IEnumerable<string> GetAllMembers(Type type) 
     {  

      var query = 
       (from member in type.GetMembers() 
       select new 
       { 
        Member = member.GetType() + " " + member.ToString() 

       } 
       ); 

      return query; 
     } 
+0

使用ToList()將解決您的問題 – Developer

+6

@Nick - 不,它不會。 – Jamiec

回答

4

試試這個

private IEnumerable<string> GetAllMembers(Type type) 
    {  

     var query = 
      from member in type.GetMembers() 
      select member.GetType() + " " + member.ToString(); 

     return query; 
    } 

你正在創建匿名類型的IEnumerable,當我想你只是想串的枚舉。

3

您與Member屬性創建匿名類型。簡單地返回字符串值。這樣你希望IEnumerable<string>

private IEnumerable<string> GetAllMembers(Type type) 
{  
    return from member in type.GetMembers() 
      select member.GetType() + " " + member.ToString(); 
} 
2

您正在從查詢中返回匿名類型(由new {}構造),而不是字符串。 您可以修改這樣例如查詢,所以結果是IEnumerable<string>

return from member in type.GetMembers() 
     select member.GetType() + " " + member.ToString(); 
2

的問題是您的查詢返回的匿名對象有一個屬性Members這是一個字符串,簡單地改變,只是返回字符串:

var query = 
      (from member in type.GetMembers() 
      select member.GetType() + " " + member.ToString() 
      ); 

    return query;