我正在寻找一种使用 l2s 根据关键字返回排名结果的方法。
我想使用一个关键字并能够使用该关键字在表中搜索该关键字.contains()
。我无法弄清楚的技巧是如何计算该 keyqord 出现的次数,然后.OrderByDescending()
根据该计数。
所以如果我有类似的事情:
string keyword = "SomeKeyword";
IQueryable<Article> searchResults = from a in GenesisRepository.Article
where a.Body.Contains(keyword)
select a;
最好的订购方式是什么searchResults
根据次数keyword
出现在a.Body
?
谢谢你的帮助。
尝试插入order by a.Body.Split(' ').Count(w=>w == keyword)
。这应该能让你看到这个概念是有效的。但是,我强烈建议最终版本将其作为选择投影的一部分,可能使用键值对,并按属性名称排序:
string keyword = "SomeKeyword";
//EDIT: restructured query to force the ordering to be done on the projection,
//not the source.
IQueryable<Article> searchResults = (from a in GenesisRepository.Article
where a.Body.Contains(keyword)
select new KeyValuePair<int, Article>(
a.Body.Split(' ').Count(w=>w == keyword), a))
.OrderBy(kvp=>kvp.Key);
原因是性能; Split().Count() 方法链是线性复杂度的,每次比较两个值都会进行评估,从而使整体排序复杂度为 N^2logN(慢)。
编辑:另外,请理解 a.Body.Contains(keyword) 不会按整个单词搜索,因此将返回包含“SomeKeywordLongerThanSearch”和“ThisIsSomeKeyword”以及“SomeKeyword”的文章。您可以通过对模式“\bSomeKeyword\b”进行正则表达式匹配来避免这种情况,它只会匹配前后紧邻单词边界的 SomeKeyword 实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)