2010-01-20 44 views
4

我使用下面的代碼返回一個IList:LINQ的轉換

public IList<string> FindCodesByCountry(string country) 
     { 
      var query = from q in session.Linq<Store>() 
         where q.Country == country 
         orderby q.Code 
         select new {q.Code}; 

      return (IList<string>) query.ToList(); 
     } 

不過,我不斷收到此錯誤:

無法投類型的對象System.Collections.Generic.List 1[<>f__AnonymousType0 1 [System.String]]'鍵入'System.Collections.Generic.IList`1 [System.String]'。

我應該回到這裏嗎?

回答

4

只要q.code是一個字符串,這應該工作: 要注意的是不能創建一個匿名對象,只是字符串被選中。

public IList<string> FindCodesByCountry(string country) 
    { 
     var query = from q in session.Linq<Store>() 
        where q.Country == country 
        orderby q.Code 
        select q.Code; 

     return query.ToList(); 
    } 
+0

哎喲.....不知道我是如何錯過的......我以爲我**有**使用**新**運算符返回一列。 – vikasde 2010-01-20 17:56:49

0

試試這個:

return query.ToList<string>(); 
2

是否有您選擇匿名類型的原因?如果不試試這個...

var query = from q in session.Linq<Store>() 
       where q.Country == country 
       orderby q.Code 
       select q.Code; 
1

如何

query.Select(s => s.ToString()).ToList(); 

或者

query.Cast<String>().ToList(); 

但我假設q.Code是一個字符串?在這種情況下,你只是想改變你的LINQ表達式:

var query = from q in session.Linq<Store>() 
        where q.Country == country 
        orderby q.Code 
        select q.Code; 
1

在查詢,而不是選擇包含字符串匿名類,只需選擇字符串本身:

var query = from q in session.Linq<Store>() 
      where q.Country == country 
      orderby q.Code 
      select q.Code; 
1

你不能將自定義類型的列表投射到類似的字符串列表中。最簡單的方法是讓你的query對象以iEnumerable字符串列表的形式開始,而不是自定義類型。您的選擇行更改爲:

select new q.Code.toString();

,你會好的。如果q.Code本身就是一個字符串,那麼.ToString()將不是必需的。