Home > OS >  Comparing two lists to return how many times a certain string is repeated
Comparing two lists to return how many times a certain string is repeated

Time:05-06

So I have two lists containing blood tests.

The first list contains tests that are offered and the second list contains tests that have previously been ordered. List 1 can have 5 tests only and list 2 can have hundreds of entries that I have retrieved from a text file.

I want to compare the lists and see how many of the tests in list 1 have been repeated on list 2 and also return how many times they were repeated.

for eg: I would like to return that test1 was repeated 5 times and test 2 repeated 3 times etc.. for the sake of statistics really.

Dim List1 As New List(Of String)()
Dim List2 As New List(Of String)()

List1.Add(test1)             
List1.Add(test2)             
List1.Add(test3)
List1.Add(test4)
List1.Add(test5)

List2.Add(test1)
List2.Add(test1)
List2.Add(test5)
List2.Add(test4)
List2.Add(test1)
List2.Add(test2)
List2.Add(test2)
List2.Add(test1)
List2.Add(test2)
List2.Add(test1)

CodePudding user response:

This might work,

    Dim List2 As New List(Of String)
    List2.Add("test1")
    List2.Add("test1")
    List2.Add("test5")
    List2.Add("test4")
    List2.Add("test1")
    List2.Add("test2")
    List2.Add("test2")
    List2.Add("test1")
    List2.Add("test2")
    List2.Add("test1")

    Dim groupedNames As IEnumerable(Of IGrouping(Of String, String))
    groupedNames = List2.GroupBy(Function(x) x)
    If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then
        For Each t As IEnumerable(Of String) In groupedNames
            Debug.Print(t(0) & " - " & t.Count.ToString)
        Next
    End If
  • Related