/// <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[]'
我知道这可能很简单,有人可以指出这里有什么问题吗?
最佳答案
当然 - 您正在尝试从声明为返回 string[]
的方法返回,但您返回的是 query - 这不是字符串在自身。将查询转换为数组的最简单方法是调用 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
参数
关于c# - Linq 返回字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7361647/