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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With