C# 将if()语句与字符串列表中的任意语句匹配

C# 将if()语句与字符串列表中的任意语句匹配,c#,regex,C#,Regex,我有一个C#程序,我需要在其中检查字符串是否与字符串列表中的任何字符串匹配 目前我的方法是: if (Regex.Matches(data, @"String1").Count > 0 || Regex.Matches(data, @"String2").Count > 0 || Regex.Matches(data, @"String3").Count > 0){ /*Code...*/ } 所以关键是看“数据”是否匹配任何字符串 这个程序要求我保留一个很长的可能字

我有一个C#程序,我需要在其中检查字符串是否与字符串列表中的任何字符串匹配

目前我的方法是:

if (Regex.Matches(data, @"String1").Count > 0 || Regex.Matches(data, @"String2").Count > 0 || Regex.Matches(data, @"String3").Count > 0){
    /*Code...*/
}
所以关键是看“数据”是否匹配任何字符串

这个程序要求我保留一个很长的可能字符串列表,并不时更新列表,所以这个系统效率很低。有什么更好的方法吗?

试试Linq:

如果必须使用正则表达式:


问问自己,正则表达式是否真的是正确的解决方案。然后问问自己如何对单个项目进行分组,并对所述分组中的每个项目执行操作。如果你愿意的话,这是一个项目集合。
  string[] toFind = new string[] {@"String1", @"String2"};

  if (toFind.Any(item => data.Contains(item))) {
    /*Code...*/
  }
  string[] patterns = new string[] {@"String1", @"String2"};

  if (patterns.Any(item => Regex.IsMatch(data, item)) {
    /*Code...*/
  }