2013-03-13 43 views
1

我有一個字符串如何檢查字符串列表是否與短語中的所有單詞匹配?

string[] arr = new string[] { "hello world", "how are you", "what is going on" }; 

的名單,我需要檢查,如果我給字符串使用的每一個字中的一個字符串在arr

讓我們說,我有

string s = "hello are going on"; 

這將是一個匹配,因爲s中的所有單詞都在arr

string s = "hello world man" 

這個人會不會是一個比賽,因爲「人」是不是在任何字符串的arr

我知道怎麼寫了「長」的方式來做到這一點,但有一個很好的LINQ查詢,我可以寫嗎?

回答

3
string[] arr = new string[] { "hello world", "how are you", "what is going on" }; 
string s = "hello are going on"; 
string s2 = "hello world man"; 
bool bs = s.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word))); 
bool bs2 = s2.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word))); 
+0

+1:優雅,簡單,好看。 SelectMany不需要像Nathan和我一樣!你可以像我在我的回答中那樣使用函數或Func委託來事件一行。 – Larry 2013-03-13 19:18:42

2
 string[] arr = new string[] { "hello world", "how are you", "what is going on" }; 

     HashSet<string> incuded = new HashSet<string>(arr.SelectMany(ss => ss.Split(' '))); 

     string s = "hello are going on"; 
     string s2 = "hello world man"; 

     bool valid1 = s.Split(' ').All(ss => incuded.Contains(ss)); 
     bool valid2 = s2.Split(' ').All(ss => incuded.Contains(ss)); 

享受! (我用的服務表現哈希集,你可以取代 「i​​ncuded」(愚蠢的錯誤)與arr.SelectMany(SS => ss.Split(」「)),獨特的()在所有情況下。

+0

在我看來不必要的內存開銷。 – FlyingStreudel 2013-03-13 19:05:39

+0

真的取決於列表的大小。對於這個小數量,你是完全正確的,如果字符串的數量超過了數千個,那麼你就會想要查找哈希值。 – IdeaHat 2013-03-18 14:57:16

0

我盡我所能一行:)

var arr = new [] { "hello world", "how are you", "what is going on" }; 

var check = new Func<string, string[], bool>((ss, ar) => 
    ss.Split(' ').All(y => ar.SelectMany(x => 
     x.Split(' ')).Contains(y))); 

var isValid1 = check("hello are going on", arr); 
var isValid2 = check("hello world man", arr); 
相關問題