I have code that ignores common words from user input:
string[] ignored_words = { "the", "and", "I" };
String[] words = UserInput.Split(' ');
foreach (string word in words)
{
if (!ignored_words.Any(word.Equals))
{
// perform actions on desired words only
}
}
This works great, unless the case is wrong ("THE" as user input will not be caught by the "the" ignored word).
How can I add an IgnoreCase clause to the Equals comparison?
if (!ignored_words.Any(w => w.Equals(word, StringComparison.CurrentCultureIgnoreCase)))
{
// ...
}
or with the static String.Equals
which has no issues with null
values:
if (!ignored_words.Any(w => string.Equals(w, word, StringComparison.CurrentCultureIgnoreCase)))
{
// ...
}
You need to pass a lambda expression:
ignored_words.Any(w => word.Equals(w, StringComparison.OrdinalIgnoreCase)
However, you can make your code much simpler and faster by using more LINQ:
foreach (string word in words.Except(ignored_words, StringComparer.OrdinalIgnoreCase))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With