How to compare two arrays of string?

前端 未结 3 1537
陌清茗
陌清茗 2021-01-16 13:21

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\", \"H         


        
相关标签:
3条回答
  • 2021-01-16 13:31

    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.

    0 讨论(0)
  • 2021-01-16 13:49

    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

    0 讨论(0)
  • 2021-01-16 13:52

    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
    
    0 讨论(0)
提交回复
热议问题