Reputation: 147
I want to compare two string arrays. I don't know how to implement this in vb.net.
Let's say I have two arrays
Dim A() As String = {"Hello", "How", "Are", "You?")
Dim B() As String = {"You", "How", "Something Else", "You")
And I want to compare A() with B() to see how they are similar and different (The order of the elements does not matter, which means the program does not check the order of the elements and only compares if there are same elements). Also the code would ignore the same elements in the same string array(like the second "You" in array B(). Then the code would return the elements these are same and the elements those are different. In this case the output message should be:
The same elements are "You" and "How"
The different element is "Something Else"
Upvotes: 2
Views: 16357
Reputation: 19404
Use Linq extensions. Except
will tell you which items are different
' ones in A but not in B
Dim result() As String = A.Except(B).ToArray()
' ones in B but not in A
Dim result() As String = B.Except(A).ToArray()
And you can use Join
to find same items
Here is One method to find same items, or different items
Dim a() as string = {"a", "b", "c"}
Dim b() as string = {"a", "b", "z"}
Dim sameItems() as String = a.Where(Function(i) b.Contains(i)).ToArray()
Array.ForEach(sameItems, Sub(i) Console.WriteLine(i))
Dim diffItems() as String = a.Where(Function(i) Not b.Contains(i)).ToArray()
Array.foreach(diffItems, Sub(i) Console.WriteLine(i))
And of course, you can use Intersect
Upvotes: 0
Reputation: 9041
With Linq
use Except()
to find the differences between the two arrays and Intersect()
to find which elements are in both arrays.
Imports System.Linq
Module Module1
Sub Main()
Dim A() As String = {"Hello", "How", "Are", "You?"}
Dim B() As String = {"You", "How", "Something Else", "You"}
Console.WriteLine("A elements not in B: " + String.Join(", ", A.Except(B)))
Console.WriteLine("B elements not in A: " + String.Join(", ", B.Except(A)))
Console.WriteLine("Elements in both A & B: " + String.Join(", ", A.Intersect(B)))
Console.ReadLine()
End Sub
End Module
Results:
A elements not in B: Hello, Are, You?
B elements not in A: You, Something Else
Elements in both A & B: How
Upvotes: 5
Reputation: 1
Set up a for loop and use .equals to compare each string at each element in the arrays. I can write the code if you need it.
Upvotes: -1