2013-03-13 50 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); 
相关问题