Linq返回字符串数组

时间:2011-09-09 12:30:21

标签: 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 (from c in db.tblSearches where c.SectionID == SectionID && c.Featured select new[] { c.Term });
    }
}

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

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

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

3 个答案:

答案 0 :(得分: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命名约定
  • 我添加了对Take的调用以使用maxToFetch参数

答案 1 :(得分: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();

答案 2 :(得分:0)

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

相关问题