How can I make Array.Contains case-insensitive on a string array?

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

I am using the Array.Contains method on a string array. How can I make that case-insensitive?

回答1:

array.Contains("str", StringComparer.OrdinalIgnoreCase); 

Or depending on the specific circumstance, you might prefer:

array.Contains("str", StringComparer.CurrentCultureIgnoreCase); array.Contains("str", StringComparer.InvariantCultureIgnoreCase); 


回答2:

Some important notes from my side, or at least putting some distributed info at one place- concerning the tip above with a StringComparer like in:

if (array.Contains("str", StringComparer.OrdinalIgnoreCase)) {} 
  1. array.Contains() is a LINQ extension method and therefore works by standard only with .NET 3.5 or higher.

  2. But: in .NET 2.0 the simple Contains() method (without taking case insensitivity into account) is at least possible like this, with a cast:

    if ( ((IList)mydotNet2Array).Contains(“str”) ) {}

  3. Addition to 1.: For the reason given above, the StringComparer in 1. works only with the following namespace inclusions (tested with .NET 3.5):

    using System;

    using System.Linq;

  4. Addition to 2.: The Contains() method does not only work with arrays, it also works with lists :-)



回答3:

new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true 


回答4:

Implement a custom IEqualityComparer that takes case-insensitivity into account.

Additionally, check this out. So then (in theory) all you'd have to do is:

myArray.Contains("abc", ProjectionEqualityComparer.Create(a => a.ToLower())) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!