4

I have two lists of strings that contain a set of names, what I want to know is how can I compare these two lists to find identical names and then write an if statement which performs actions based on the comparison.

List 1: Philip Bob Michael

List 2: James Peter Bob

0

4 Answers 4

6

One of the many linq extensions is Intersect which returns the elements common to both:

Dim names1 = {"Philip", "Bob", "Michael"}
Dim names2 = {"James", "Ziggy", "Bob", "Hoover"}

Dim commonNames = names1.Intersect(names2).ToArray()
For Each n As String In commonNames
    Console.WriteLine(n)
Next

Output:

Bob

There are a bunch of these, you can type . (dot) and browse them thru Intellisense and read the 1-liner of what they do and at least become aware they exist.

Sign up to request clarification or add additional context in comments.

Comments

1

This might be helpful

    lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase)
    PrintList(lstNew)

    Console.ReadLine()
    End Sub

     Private Sub PrintList(ByVal str As IEnumerable(Of String))
     For Each s In str
     Console.WriteLine(s)
     Next s
     Console.WriteLine("-------------")

Reference http://www.devcurry.com/2010/07/list-common-elements-between-two-list.html?m=1

Comments

1

First time writing VB. You can use the nested loops below to find an identical. If you want case to matter, replace equalsIgnoreCase with just equals

    Dim list1() as String ={"name1","name2"}
    Dim list2() as String ={"name3","name2"}
    For Each str as String In list1
        For Each names as String In list2
          If String.Compare(str,names) = 0 Then
           Console.WriteLine(str+" "+names)
          End If
        Next names
    Next str

Comments

0
    Dim names1 = {"Philip", "Ziggy", "Bob", "Michael", "James"}
    Dim names2 = {"James", "Ziggy", "Bob", "Michael", "Hoover"}

    Dim commonNames = names1.Intersect(names2).ToArray()
    Dim Match As String = ""
    Dim NumberOfMatches = 0

    For Each n As String In commonNames
        Match += n.ToString + " "
        NumberOfMatches += 1
    Next

    TextBox1.Text = Match
    TextBox2.Text = NumberOfMatches

Output will contain all of the identical names & Number of Matches: Ziggy Bob Michael James & 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.