在字符串列表中查找子字符串

时间:2020-01-07 14:06:59

标签: c# string list

我有一个字符串列表,并且我添加了多个字符串。 例如:l1是具有三个值的列表

List<string> l1 = new List<string> 
{
     "issue: there are multiple data errors ",
     "resolution: you can correct the data or /n raise an SR on this issue",
     "rootfix: you need to be contious while entering the data "
};

现在我需要检查此列表是否包含所有三个键字符串。

List<string> keyWords = new List<string> { "isue", "resolution", "rootfix" };

我不认为我可以对此进行Contains操作,因为上述字符串是列表字符串的子字符串。

请让我知道/ logic是否有可用功能。

如果列表中所有三个子字符串都存在,那么我需要返回布尔值

3 个答案:

答案 0 :(得分:2)

您可以检查单词集中的All项中的Any关键字是否与关键字String.Contains匹配

List<string> keyWords = new List<string>{"issue","resolution","rootfix"};

List<string> wordSet = new List<string>{"issue: there are multiple data errors ", "resolution: you can correct the data or /n raise an SR on this issue", "rootfix: you need to be contious while entering the data "};

bool result = keyWords.All(x => wordSet.Any(w => w.Contains(x)));

对于人类来说,从内而外阅读可能更容易

答案 1 :(得分:1)

我不清楚您的示例是否在您的List<string>中显示了三个分离的字符串,或者它们是否是单个字符串。 / p>

在第一种情况下,List<string>中有三个单独的字符串,您可以使用类似以下内容的东西:

bool isInList = l1.Any(x => x.StartsWith("issue")) &&
                l1.Any(x => x.StartsWith("resolution")) &&
                l1.Any(x => x.StartsWith("rootfix"));

如果在true中找到了所有匹配的字符串,它将返回l1

如果是第二种情况,则为一个字符串,其中包含您所描述的值:

string l1 = "{\"issue: there are multiple data errors \", \"resolution: you can correct the data or /n raise an SR on this issue\", \"rootfix: you need to be contious while entering the data \"}";
bool isInString = l1.Contains("\"issue") &&
                  l1.Contains("\"resolution") &&
                  l1.Contains("\"rootfix"))

这将返回true,其中所有三个名称都出现在同一字符串中。

答案 2 :(得分:0)

这应该有效:

var data = new []{"issue: there are multiple data errors ", "resolution: you can correct the data or /n raise an SR on this issue", "rootfix: you need to be contious while entering the data "};

bool flag = (
    data.Any(d => d.StartsWith("issue:")) &&
    data.Any(d => d.StartsWith("resolution:")) &&
    data.Any(d => d.StartsWith("rootfix:"))
    );