2011-09-09 109 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()在返回语句的末尾。