2011-09-09 113 views
6
/// <summary> 
/// Returns list of popular searches 
/// </summary> 
public static string[] getPopularSearches(int SectionID, int MaxToFetch) 
{ 
    using (MainContext db = new MainContext()) 
    { 
     return (from c in db.tblSearches where c.SectionID == SectionID && c.Featured select new[] { c.Term }); 
    } 
} 

我看了看其他的問題,但他們似乎略有不同,我得到的錯誤:LINQ的返回字符串數組

Cannot implicitly convert type 'System.Linq.IQueryable<string[]>' to 'string[]' 

我知道這可能是簡單的,可能有人指出,什麼是錯在這裏請?

+0

是否有特殊原因需要返回數組? IEnumerable 將在大多數情況下更可取,除非調用代碼明確需要數組(不太可能) – MattDavey

回答

15

當然 - 你試圖從聲明爲返回string[]的方法返回,但你要返回一個查詢 - 本身不是字符串。將查詢轉換爲數組最簡單的方法是調用ToArray擴展方法。

但是,因爲您已經爲選擇了查詢中每個元素的字符串數組,實際上它會返回string[][]。我懷疑你真的想選擇每個查詢元素一個字符串,然後轉換整個事情到一個數組,即這樣的代碼:

public static string[] GetPopularSearches(int sectionID, int maxToFetch) 
{ 
    using (MainContext db = new MainContext()) 
    { 
     var query = from c in db.tblSearches 
        where c.SectionID == sectionID && c.Featured 
        select c.Term; 
     return query.Take(maxToFetch) 
        .ToArray(); 
    } 
} 

需要注意的是:

  • 我改名方法和參數匹配.NET命名約定
  • 我爲了使用maxToFetch參數
+0

真棒一如既往謝謝你:D –

+3

嘿喬恩我爲你做了一張照片:) http://我.stack.imgur.com/4CSKh.png –

4

您正試圖返回一個無實體化的查詢。該查詢僅在枚舉時才被評估。幸運的是,ToArray方法避免了枚舉和存儲。簡單地將它添加到查詢的最後應該可以修復所有問題。

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select new[] { c.Term } 
).ToArray(); 

編輯

尋找更詳細,也許是:

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select new[] { c.Term } 
).SelectMany(x => x).ToArray(); 

扁平化查詢的結果,甚至(少冗餘):

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select c.Term 
).ToArray(); 
+0

如果我想要兩個字段,而不僅僅是c.Term,那會是什麼樣子? –

+0

@AlanFisher你可以選擇一個匿名對象:'... select new {c.Term,c.SectionID}' – spender

0

添加添加一個電話Take。 ToArray()在返回語句的末尾。