how to Find and count duplicate numbers in a string array in vb.net?

后端 未结 4 2120
旧时难觅i
旧时难觅i 2020-12-12 08:32

how to count the duplicate numbers exist in a string or integer array in vb.net?

Dim a as string = \"3,2,3\"

from the above

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 08:54

    You've already got some good answers to choose from, but I thought you'd be interested in a one liner solution.

    Module Module1
        Sub Main()
            Dim str() As String = "1,2,1,2,3,1,0,1,4".Split(","c)
            str.Distinct().ToList().ForEach(Sub(digit) Console.WriteLine("{0} exists {1}", digit, str.Count(Function(s) s = digit)))
            Console.ReadLine()
        End Sub
    End Module
    

    Explanation as to what's happening:

    • str.Distinct() - Returns an IEnumerable object of all unique items in the array
    • .ToList() - Turns the IEnumerable object into a List
    • .ForEach() - Iterates through the List
      • Sub(digit) - Defines an Action delegate to perform on each element. Each element is named digit during each iteration.
      • You should know what Console.WriteLine() is doing
      • str.Count() - Will count each occurrence a digit that satisfies a condition
        • Function(s) s = digit - Defines a Func delegate that will count each occurrence of digits in the array. Each element, in str(), during the Count iterations are stored in the variable s and if it matches the digit variable from Sub(digit) it will be counted

    Results:

    1 exists 4
    2 exists 2
    3 exists 1
    0 exists 1
    4 exists 1
    

提交回复
热议问题