Dinesh M Dinesh M - 5 months ago 11x
Vb.net Question

comparing two strings using IEnumerable

I want to compare lines between two lines and print them. I have the following code to do this

Dim linesA As [String]() = File.ReadAllLines(TextBox1.Text)
Dim linesB As [String]() = File.ReadAllLines(TextBox2.Text)

Dim onlyB As IEnumerable(Of [String]) = linesB.Except(linesA)

It does not do the job when there are some extra tabs that occur before the string
How do I eliminate all the tabs and spaces in a line before I compare them?


If one line has an leading tab and the other doesnt, they are not equal so the default comparison doesn't work. However Except has an overload which allows you to specify a custom Equality comparer where you can provide your own comparison logic:

Public Class LineComparer
    Implements IEqualityComparer(Of String)

    Public Function Equals1(x As String, y As String) As Boolean _
                         Implements IEqualityComparer(Of String).Equals
        Return (String.Compare(x.Trim(), y.Trim(), StringComparison.OrdinalIgnoreCase) = 0)
    End Function

    Public Function GetHashCode1(obj As String) As Integer _
                              Implements IEqualityComparer(Of String).GetHashCode
        Return obj.Trim().GetHashCode
    End Function
End Class

Note that Except uses GetHashCode1 for the comparing.


Dim justB = linesB.Except(linesA, New LineComparer())

The difference between this and Mr Blackwood's answer is that this doesn't change the data loaded for ListA or ListB. It simply ignore tabs and spaces when comparing. It is not clear which one is what you are after.