Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two lists of strings to find identical strings

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

like image 716
Zochonis Avatar asked Feb 07 '23 14:02

Zochonis


2 Answers

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.

like image 99
Ňɏssa Pøngjǣrdenlarp Avatar answered Feb 10 '23 04:02

Ňɏssa Pøngjǣrdenlarp


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

like image 43
Seda Avatar answered Feb 10 '23 04:02

Seda