.net 如何在字符串数组上使 Array.Contains 不区分大小写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/952679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make Array.Contains case-insensitive on a string array?
提问by Mike Cole
I am using the Array.Containsmethod on a string array. How can I make that case-insensitive?
我Array.Contains在字符串数组上使用该方法。我怎样才能使不区分大小写?
回答by Mehrdad Afshari
array.Contains("str", StringComparer.OrdinalIgnoreCase);
Or depending on the specific circumstance, you might prefer:
或者根据具体情况,您可能更喜欢:
array.Contains("str", StringComparer.CurrentCultureIgnoreCase);
array.Contains("str", StringComparer.InvariantCultureIgnoreCase);
回答by Philm
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:
我这边的一些重要说明,或者至少将一些分布式信息放在一个地方 - 关于上面带有 StringComparer 的提示,例如:
if (array.Contains("str", StringComparer.OrdinalIgnoreCase))
{}
array.Contains()is a LINQ extension method and therefore works by standard only with .NET 3.5 or higher, needing:using System;using System.Linq;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<string>)mydotNet2Array).Contains(“str”) ) {}As the Contains() method is part of the IList interface, this works not only with arrays, but also with lists, etc.
array.Contains()是一种 LINQ 扩展方法,因此仅适用于 .NET 3.5 或更高版本的标准,需要:using System;using System.Linq;但是:在 .NET 2.0 中,简单的
Contains()方法(不考虑不区分大小写)至少可以像这样,使用强制转换:if ( ((IList<string>)mydotNet2Array).Contains(“str”) ) {}由于 Contains() 方法是 IList 接口的一部分,这不仅适用于数组,还适用于列表等。
回答by Kon
Implement a custom IEqualityComparerthat takes case-insensitivity into account.
实现一个自定义的IEqualityComparer,它考虑到不区分大小写。
Additionally, check thisout. So then (in theory) all you'd have to do is:
此外,检查这出。那么(理论上)你所要做的就是:
myArray.Contains("abc", ProjectionEqualityComparer<string>.Create(a => a.ToLower()))
回答by Darin Dimitrov
new[] { "ABC" }.Select(e => e.ToLower()).Contains("abc") // returns true

