2014-11-01 123 views
-1

我對這個有點醃製。查找關鍵字最高的列表中的字符串

所以我有什麼是關鍵字列表,例如:

this, 
keyword, 
apple, 
car, 
banana 

我有一個字符串列表,我想找到的是蒙山這些關鍵字的最高計數的字符串,我開始.Any(),但是這會返回第一個字符串與關鍵字的一個匹配。

我的字符串列表:

This is a car. (2 keywords) 
This is a sentence with the keyword apple, (3 keywords) 
This sentence contains the keyword apple and another keyword car, (5 keywords) 
The next sentence contains only car (1 keyword) 

現在我想找到什麼是第三句(用5,最,關鍵字)。

這是一種算法,去我的頭有點上面,還我想在LINQ,也許我應該接近它以其他方式

誰能幫我這個嗎?

感謝

編輯:

確定我得到了它與MaxBy()方法來工作。

現在我絆倒了另一個問題,讓我解釋什麼,我在我的項目做:

基本上我有種子名單

Torrent.Title 
Torrent.Seeds 

現在,我得到的結果與MaxBy的洪流標題,但這不考慮種子。我會建議這樣做:對最大關鍵字進行一些排序,然後對種子進行排序。有人認爲這是可能的嗎?

會這樣嗎?

var results = torrents.OrderByDescending(torrent => torrent.Title.Replace(".", " ").Replace("-", " ").Split().Count(Settings.FilterKeywords.Split(',').Contains)).ThenByDescending(torrent => torrent.Seeds); 

return results.First(); 
+0

嗨,堆棧溢出是有點不同於互聯網論壇網站。在這裏,我們喜歡每個問題堅持一個主題。如果你的問題得到了一個有用的答案(它的確如此),那麼很好,將答案標記爲已接受,也許可以贊成。如果在應用解決方案後出現任何*新問題,請發起一個新問題。 – 2014-11-01 22:34:32

回答

3

這將是使用MaxBy方法簡單:

var keywords = new HashSet<string> { "this", "apple", "car", "keyword" }; 

var sentence = sentences.MaxBy(x => x.Split().Count(keywords.Contains)); 

不使用第三方庫:

sentences 
.Select(s => new { Sentence = s, Count = s.Split().Count(keywords.Contains) }) 
.OrderByDescending(x => x.Count).First().Sentence; 

可以Split之前使用ToLower如果你想不區分大小寫。

+0

linq中不支持maxby(錯誤'System.Collections.Generic.List '不包含'MaxBy'的定義,也沒有接受'System'的第一個參數的擴展方法'MaxBy' .Collections.Generic。列表'可能被發現(你是否缺少使用指令或程序集引用?)) 我正在使用c#btw。 – 2014-11-01 08:51:06

+0

它來自morelinq庫https://code.google.com/p/morelinq/ – 2014-11-01 08:52:05

+0

哦,我不想讓它變得複雜,但是字符串列表基本上是包含字符串的對象列表,例如object.Title =「這句話包含關鍵字蘋果和另一個關鍵詞汽車」; – 2014-11-01 08:53:50

-2

是的,我想我回答我自己的問題:

var results = torrents.OrderByDescending(torrent => torrent.Title.Replace(".", " ").Replace("-", " ").Split().Count(Settings.FilterKeywords.Split(',').Contains)).ThenByDescending(torrent => torrent.Seeds); 

return results.First(); 

我要感謝大家的意見!