C# Linq返回字符串数组 // ///返回常用搜索列表 /// 公共静态字符串[]GetPopularSearchs(int SectionID,int MaxToFetch) { 使用(MainContext db=newmaincontext()) { 返回(从db.tblsearch中的c返回,其中c.SectionID==SectionID&&c.selected选择new[]{c.Term}); } }

C# Linq返回字符串数组 // ///返回常用搜索列表 /// 公共静态字符串[]GetPopularSearchs(int SectionID,int MaxToFetch) { 使用(MainContext db=newmaincontext()) { 返回(从db.tblsearch中的c返回,其中c.SectionID==SectionID&&c.selected选择new[]{c.Term}); } },c#,asp.net,arrays,string,linq,C#,Asp.net,Arrays,String,Linq,我看了其他问题,但它们似乎略有不同,我得到了错误: /// <summary> /// Returns list of popular searches /// </summary> public static string[] getPopularSearches(int SectionID, int MaxToFetch) { using (MainContext db = new MainContext()) { return (fr

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

/// <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 });
    }
}
无法将类型“System.Linq.IQueryable”隐式转换为“string[]”

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

您正试图返回一个未实现的查询。查询仅在枚举时计算。幸运的是,ToArray方法减轻了枚举和存储的痛苦。只需将其添加到查询的末尾,就可以解决所有问题

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

更详细地看,也许:

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select new[] { c.Term }
).ToArray();
要展平查询结果,甚至(减少冗余),请执行以下操作:


当然-您试图从声明为返回
字符串[]
的方法返回,但您返回的是一个查询-它本身不是字符串。将查询转换为数组的最简单方法是调用扩展方法

但是,由于您已经为查询中的每个元素选择了一个字符串数组,因此实际上会返回
string[][]
。我怀疑您真的希望为每个查询元素选择一个字符串,然后将整个字符串转换为一个数组,即如下代码:

return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select c.Term
).ToArray();
请注意:

  • 我已经重命名了方法和参数以匹配.NET命名约定
  • 我添加了对
    Take
    的调用,以便使用
    maxToFetch
    参数

在return语句末尾添加.ToArray()

是否有特殊原因需要返回数组?IEnumerable在大多数情况下更可取,除非调用代码特别需要一个数组(不太可能),如果我想要两个字段,而不仅仅是c.Term,那会是什么样子?@AlanFisher您可以选择一个匿名对象:
…选择新的{c.Term,c.SectionID}
return (
    from c in db.tblSearches 
    where c.SectionID == SectionID && c.Featured 
    select c.Term
).ToArray();
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();
    }
}