忽略Linq.Any中的案例,C#

时间:2015-04-20 14:12:25

标签: c# linq

我的代码忽略了用户输入的常用词:

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
    }
}

这很有效,除非案例错误(&#34; THE&#34;因为用户输入不会被&#34;&#34;被忽略的词)。< / p>

如何在等于比较中添加IgnoreCase clause

3 个答案:

答案 0 :(得分:16)

if (!ignored_words.Any(w => w.Equals(word, StringComparison.CurrentCultureIgnoreCase)))
{
   // ...
}

或与null值无关的静态String.Equals

if (!ignored_words.Any(w => string.Equals(w, word, StringComparison.CurrentCultureIgnoreCase)))
{
   // ...
}

答案 1 :(得分:8)

您需要传递lambda表达式:

ignored_words.Any(w => word.Equals(w, StringComparison.OrdinalIgnoreCase)

但是,通过使用更多LINQ:

,您可以使代码更简单,更快捷
foreach (string word in words.Except(ignored_words, StringComparer.OrdinalIgnoreCase))

答案 2 :(得分:6)

作为一种更有效的方式:

// note: the exact comparer deserves some thought; cultural? ordinal? invariant?
var ignored_words = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase)
{
    "the", "and", "I"
};

foreach (string word in words)
{
    if (!ignored_words.Contains(word))
    {
        // perform actions on desired words only
    }
}