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

        For Each c In lstchars2

        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

3 Years
Discussion Span
Last Post by kRod
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 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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.