Rich
Rich

Reputation: 6573

How to ignore case using the Zip operator in Linq

I have the following code using the Zip operator and Linq to compare the first 100 characters of two strings:

Dim str1 As String = "My first string here..."
Dim str2 As String = "My FIRST string here..."

Dim areEqual As Boolean = str1.Zip(str2, Function(x1,x2) x1 = x2).Take(100).All(Function(equal) equal)

Console.WriteLine(areEqual)

How could I make the comparison case insensitive?

Upvotes: 1

Views: 53

Answers (3)

D Stanley
D Stanley

Reputation: 152624

Using Zip seems like an inefficient way to compare the first 100 characters of two strings. You can already compare substrings using String.Compare:


Dim minLen as Integer = 100
If str1.Length < minLen Then minLen = str1.Length
If str2.Length < minLen Then minLen = str2.Length


Dim areEqual as Boolean = (string.Compare(str1.Substring(0, minLen), str2.Substring(0, minLen), StringComparison.OrdinalIgnoreCase) = 0)

Upvotes: 3

Andrew Morton
Andrew Morton

Reputation: 25057

To account for different cultures, something with StringComparison would be in order:

Dim areEqual As Boolean = str1.Zip(str2, Function(x1, x2) String.Compare(x1, x2, StringComparison.InvariantCultureIgnoreCase) = 0).
    Take(100).
    All(Function(equal) equal)

Select the appropriate StringComparison for your case.

For informative and amusing interesting information on the subject, see the video by Jon Skeet Jon Skeet - "Back to basics: the mess we've made of our fundamental data types". (It's better to watch from the start, but that's where the part about text starts.)

Upvotes: 2

l&#39;L&#39;l
l&#39;L&#39;l

Reputation: 47284

Maybe try using Char.ToLower():

Dim areEqual As Boolean = str1.Zip(str2, Function(x1, x2) Char.ToLower(x1) = Char.ToLower(x2)).Take(100).All(Function(equal) equal)

Upvotes: 1

Related Questions