How to compare two arrays of string?
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
bill
Updated on June 13, 2022Comments
-
bill almost 2 years
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"