I was going to make this a comment to Dan's answer, but it started getting quite long (and I wanted to try and actually code it to see if I remembered how).
Assuming excludedWords
is big and doesn't change between builds of the application (or if it does you have the ability to replace a single dll), you should build a dll containing the compiled regex representing it to get a much better search then you would if you used that linq expression.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
namespace RegexLibAssemblyBuilder
{
public class RegexCompilationTest
{
public static IEnumerable<string> ExcludedWords() {...}
public static void Main()
{
//build pattern
var excludedWordsRegex = new StringBuilder();
bool first = true;
foreach (var word in ExcludedWords())
{
if (!first)
{
excludedWordsRegex.Append("|");
}
excludedWordsRegex.Append(Regex.Escape(word));
first = false;
}
// Define regular expression here
var expr = new RegexCompilationInfo(excludedWordsRegex.ToString(),
RegexOptions.None,
"ExcludedWordsRegex",
"Utilities.RegularExpressions",
true);
//add other assembly attributes you want just like this
ConstructorInfo ctor = typeof(System.Reflection.AssemblyTitleAttribute).GetConstructor(new[] { typeof(string) });
CustomAttributeBuilder[] attBuilder = { new CustomAttributeBuilder(ctor, new object[] { "General-purpose library of compiled regular expressions" }) };
Regex.CompileToAssembly(new[] { expr }, new AssemblyName("RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null"), attBuilder);
}
}
}
Then in code you could use it like this (after linking your project to this new assembly):
private static readonly Regex excludedWords= new ExcludedWordsRegex();
private bool IsValid(string code)
{
if (this.chkLessThan2Letters.Checked && matchCode.IsMatch(code))
{
return false;
}
if (excludedWords.IsMatch(code))
{
return false;
}
...
newCodes
? Using aHashSet<string>
here will be beneficial. \$\endgroup\$ – spender May 4 '12 at 17:15newCodes.Contains
should be very fast, you could do that one first and save time on average. \$\endgroup\$ – harold May 4 '12 at 17:20