c# – Linq返回字符串数组
发布时间:2020-12-15 18:15:52 所属栏目:百科 来源:网络整理
导读:/// summary/// Returns list of popular searches/// /summarypublic static string[] getPopularSearches(int SectionID,int MaxToFetch){ using (MainContext db = new MainContext()) { return (from c in db.tblSearches where c.SectionID == SectionI
/// <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[]' 我知道这可能很简单,有人可以指出这里有什么问题吗? 解决方法
当然 – 你试图从声明为返回字符串[]的方法返回,但是你要返回一个查询 – 它本身不是一个字符串.将查询转换为数组的最简单方法是调用
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参数 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |