locked
Visual Basic count the number of values in an array? RRS feed

  • Question

  • in Visual Basic is there a way to count the number of values in an array?
    Sunday, January 12, 2020 5:05 AM

Answers

  • Is there a way to do it in a form application? I would like to get the count of unique values also a list of those unique value in the inventory transfer # box. The values will be ascending order if that helps.
    My last code samples were all done in button click event of a form.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by jbrotto Wednesday, January 22, 2020 1:08 AM
    Sunday, January 12, 2020 10:24 PM
  • Hi jbrotto,

    Did you solve your problem? If your question has been answered then please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by jbrotto Wednesday, January 22, 2020 1:08 AM
    Tuesday, January 21, 2020 9:45 AM

All replies

  • Hi,
    to get the numbeer of values (items) in an array you can use the Count property like in this console demo:

    Module Module1
      Sub Main()
        Try
          Call (New Demo).Execute()
        Catch ex As Exception
          Dim ex1 = ex
          While ex1 IsNot Nothing
            Console.WriteLine(ex1.Message)
            ex1 = ex1.InnerException
          End While
        End Try
        Console.WriteLine("Continue enter key")
        Console.ReadKey()
      End Sub
    
      Friend Class Demo
    
        Friend Sub Execute()
          Dim arr = GetArray()
          Dim cnt = arr.Count
          Console.WriteLine(cnt)
          '
          ' iterate from first to last item in Array
          For i = arr.GetLowerBound(0) To arr.GetUpperBound(0)
            Console.WriteLine(arr(i))
          Next
        End Sub
    
        Private Function GetArray() As String()
          Dim l As New List(Of String)
          For i = 1 To 10
            l.Add($"Item {i}")
          Next
          Return l.ToArray
        End Function
    
      End Class
    
    End Module


    --
    Best Regards / Viele Grüße
    Peter Fleischer (former MVP for Developer Technologies)
    Homepage, Tipps, Tricks

    Sunday, January 12, 2020 6:34 AM
  • For unidimensional arrays, use the Length property too:

       Dim myarray() As Integer = {10, 20, 30}

     

       Console.WriteLine(myarray.Length) ' prints "3"

     

    Sunday, January 12, 2020 8:49 AM
  • Is there a way to count the unique values in the array?
    Sunday, January 12, 2020 3:20 PM
  • The easy way is to use GroupBy.

    The following shows a GroupBy with a string array were the comparison is gone case insensitive which is followed by GroupBy on integers

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        Dim Names() As String =
                {
                    "John", "John", "Abbey", "Larry",
                    "LARRY", "Larry", "Charles"
                }
    
        Dim groupedNames = Names.GroupBy(Function(item) item, StringComparer.CurrentCultureIgnoreCase).
                Select(Function(g) New With {
                          .Name = g.Key,
                          .Count = g.Count()}).
                ToArray()
    
        For Each currentNameItem In groupedNames
            Console.WriteLine($"{currentNameItem.Name} ({currentNameItem.Count})")
        Next
    
        Console.WriteLine()
    
        Dim Numbers() As Integer = {1, 2, 3, 1, 3, 2, 1, 1}
    
        Dim groupedNumbers = Numbers.GroupBy(Function(item) item).
                Select(Function(g) New With {
                          .Number = g.Key,
                          .Count = g.Count()}).ToArray()
    
        For Each currentItem In groupedNumbers
            Console.WriteLine($"{currentItem.Number} ({currentItem.Count})")
        Next
    
    
    End Sub

    Both results you can apply the .Count property to know the count.

    Here is another example not performing case insensitive result and using a strong type result rather than the examples above which are anonymous type results and using LINQ rather than Lambda (each has there place).

    Dim wordList = New List(Of String) From {"Hello", "Goodnight", "Hello", "Good", "Last"}
    
    Dim wordGroup As IOrderedEnumerable(Of WordOccurrenceContainer) =
            (
                From word In wordList
                Group wordElement = word By token = word Into Group
                Select New WordOccurrenceContainer With {.Word = token, .Occurrences = Group.Count}
            ).
            ToList.
            OrderBy(Function(anonymous) anonymous.Word)
    
    Return wordGroup
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Sunday, January 12, 2020 5:57 PM
  • Is there a way to do it in a form application? I would like to get the count of unique values also a list of those unique value in the inventory transfer # box. The values will be ascending order if that helps.
    • Edited by jbrotto Sunday, January 12, 2020 9:37 PM picture
    Sunday, January 12, 2020 9:20 PM
  • I would like to take the text in box from inventory transfer # and get a count of unique values. Also the total number of unique values.

    Sunday, January 12, 2020 9:35 PM
  • Hello,

    Example 1, get unique numbers in a TextBox.

     

    Get total for above

    Dim distinctNumbersInTextBox = numbers.Distinct().ToList()
    Dim distinctTotal = distinctNumbersInTextBox.Count

    To get total count of distinct numbers in TextBox and count for each number

    Dim numbers = TextBox1.Lines.Select(Function(value) Integer.Parse(value))
    Dim groupedNumbers = numbers.GroupBy(Function(item) item).
            Select(Function(g) New With {
                      .Number = g.Key,
                      .Count = g.Count()}).ToArray()
    
    Console.WriteLine($"{groupedNumbers.Length} distinct values")
    For Each currentItem In groupedNumbers
        Console.WriteLine($"   {currentItem.Number} ({currentItem.Count})")
    Next

    Now let's use names in a TextBox

    Dim groupedNames = TextBox1.Lines.Select(Function(value) value).GroupBy(Function(item) item).
            Select(Function(g) New With {
                      .Number = g.Key,
                      .Count = g.Count()}).ToArray()
    
    MessageBox.Show($"{groupedNames.Length} distinct values")
    For Each currentItem In groupedNames
        MessageBox.Show($"   Name: {currentItem.Number} Count: ({currentItem.Count})")
    Next


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, January 12, 2020 9:55 PM
  • Is there a way to do it in a form application? I would like to get the count of unique values also a list of those unique value in the inventory transfer # box. The values will be ascending order if that helps.
    My last code samples were all done in button click event of a form.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by jbrotto Wednesday, January 22, 2020 1:08 AM
    Sunday, January 12, 2020 10:24 PM
  • Hi jbrotto,

    Did you solve your problem? If your question has been answered then please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by jbrotto Wednesday, January 22, 2020 1:08 AM
    Tuesday, January 21, 2020 9:45 AM