Linq返回字符串数组

Tom*_*len 6 c# linq asp.net arrays string

/// <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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

我看了其他问题,但它们似乎略有不同,我得到了错误:

Cannot implicitly convert type 'System.Linq.IQueryable<string[]>' to 'string[]'
Run Code Online (Sandbox Code Playgroud)

我知道这可能很简单,有人可以指出这里有什么问题吗?

Jon*_*eet 15

当然 - 你试图从声明返回a的方法返回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();
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:

  • 我已重命名方法和参数以匹配.NET命名约定
  • 我已经添加了一个调用Take来使用该maxToFetch参数


spe*_*der 5

您正在尝试返回未具体化的查询。仅当查询被枚举时才会对其求值。幸运的是,ToArray 方法消除了枚举和存储的痛苦。只需将其添加到查询末尾即可解决所有问题。

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

编辑

更详细地看,也许:

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

扁平化查询结果,甚至(更少冗余):

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select c.Term
).ToArray();
Run Code Online (Sandbox Code Playgroud)