假设一个字符串数组:
var stringArray = "a,b,c,".Split(',');
在调用LINQ的Contains()方法时,默认是区分大小写的:
stringArray.Contains("A");
如何让之不区分大小写?
最简单的解决方法:
stringArray.Contains("A", StringComparer.OrdinalIgnoreCase);
stringArray.Contains("A") || stringArray.Contains("a")
//var stringArray = ("A,B,C,").ToUpper().Split(','); //或者 //var stringArray = ("a,b,c,").ToLower().Split(','); //没必要纠结其他的了吧,难道还去实现IEqualityComparer<String>啊
就是不想每次手工进行大小写转换
首先感谢一下DUDU,让我下午还能研究一点东东,贴上代码如下,是VB的,凑合着看吧。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myString = "a,b,c".Split(",")
Dim ignoreCaseComparer As IgnoreCaseComparer = New IgnoreCaseComparer()
MessageBox.Show(myString.Contains("a", ignoreCaseComparer))
MessageBox.Show(myString.Contains("B", ignoreCaseComparer))
End Sub
Class IgnoreCaseComparer
Implements IEqualityComparer(Of String)
Public myComparer As CaseInsensitiveComparer
Public Sub New()
myComparer = CaseInsensitiveComparer.DefaultInvariant
End Sub
Public Sub New(myCulture As CultureInfo)
myComparer = New CaseInsensitiveComparer(myCulture)
End Sub
#Region "IEqualityComparer<string> Members"
Public Overloads Function Equals(x As String, y As String) As Boolean Implements IEqualityComparer(Of String).Equals
If myComparer.Compare(x, y) = 0 Then
Return True
Else
Return False
End If
End Function
Public Overloads Function GetHashCode(obj As String) As Integer Implements IEqualityComparer(Of String).GetHashCode
Return obj.ToLower().GetHashCode()
End Function
#End Region
End Class
End Class
嗯,实现IEqualityComparer<string>接口是解决之道,有没有更简单的方法呢?
@dudu:
找了一下,本来希望能在CultureInfo.CurrentCulture中找到设置当前比较方法默认值的选项,
很遗憾,没有找到,你可以到MSDN上找微软提下建议,
我也希望能够通过这样一句语句
CultureInfo.CurrentCulture.CompareInfo.IgnoreCase=true
然后整个软件就是这样了。
这个直接自定义一个比较器吧~要不然就需要先转换大小写~
先把对象中的值转成大写或者小写,再使用Contains就不用判断了。