Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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 "a" variable i want a count of "3" as 2 (i mean 3 exist 2 times) and "2" as "1". So how do i make it in vb.net?????

Actually i will get the above string "a" from the sql database. so i dont know which numbers are there. That's why i am asking here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<T>
  • .ForEach() - Iterates through the List<T>
    • 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...