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"

这个不匹配,因为“man”不在任何字符串中arr

我知道如何编写一个“更长”的方法来做到这一点,但是我可以编写一个不错的 linq 查询吗?

4

3 回答 3

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)));
于 2013-03-13T19:03:25.557 回答
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));

享受!(我将哈希集用于性能,您可以在所有情况下用 arr.SelectMany(ss => ss.Split(' ')).Unique() 替换“包含”(愚蠢的错字)。

于 2013-03-13T19:02:25.573 回答
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);
于 2013-03-13T19:13:05.343 回答