I have a question about the string.intersect method.

I am not getting the results I expect.

        Dim lstChars1() As Char = "hello dolly" 'TextBox1.Text.ToCharArray
        Dim lstchars2() As Char = "help melanie" 'TextBox2.Text.ToCharArray

        Dim lst1 As New List(Of String)
        Dim lst2 As New List(Of String)

        For Each c In lstChars1
            lst1.Add(c.ToString)
        Next

        For Each c In lstchars2
            lst2.Add(c)
        Next

        Dim lstNew As IEnumerable(Of String) = Nothing
        lstNew = lst1.Intersect(lst2, StringComparer.OrdinalIgnoreCase)

lstNew contains "h", "e", "l", " "
I expected another 'l", What's the reason for this behavior? I have also attempted this using arrays and received the same values.

Thanks In Advance

00|01|02|03|04|05|06|07|08|09|10|11
h |e |l |l |o |  |d |o |l |l |y |
h |e |l |p |  |m |e |l |a |n |i |e

You can see from this simple table that only indexes 0,1, and 2 contain the same charactrers in both strings and that is what Intersect is returning.

If you're expecting something else you'll have to be more clear giving expected input and expected output.

Edited 2 Years Ago by tinstaafl

Intersection returns only the elements that are contained in both sets. It doesn' rtell you how many or at which positions they are.

Yes I understand that it returns the matching elements. I went to the MSDN and read that it only returns Distinct elements that match so that is probably why the one l is all I got back. Also, I didn't realize they had to be in the same position(index) of the collection.

I guess I will have to find some other method to get all the matching elements whether or not they're Distinct. I was hoping that was my answer as it's not a lot of coding but what would be the fun!!!!

Very True Minimalist I just tested my code and it didn't matter they just have to be distinct

This question has already been answered. Start a new discussion instead.