且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 vb.net 中的字符串数组中查找和计算重复数字?

更新时间:2022-10-30 20:59:39

您已经有一些不错的答案可供选择,但我认为您会对单行解决方案感兴趣.

模块 Module1子主()Dim str() As String = "1,2,1,2,3,1,0,1,4".Split(","c)str.Distinct().ToList().ForEach(Sub(digit) Console.WriteLine("{0} 存在 {1}", digit, str.Count(Function(s) s = digit)))Console.ReadLine()结束子终端模块

对正在发生的事情的解释:

  • str.Distinct() - 返回数组中所有唯一项的 IEnumerable 对象
  • .ToList() - 将 IEnumerable 对象变成 List
  • .ForEach() - 遍历 List
    • Sub(digit) - 定义一个 Action 委托对每个元素执行.在每次迭代期间,每个元素都被命名为 digit.
    • 你应该知道 Console.WriteLine() 在做什么
    • str.Count() - 将每次出现计算一个满足条件的数字
      • Function(s) s = digit - 定义一个 Func 委托将计算数组中每次出现的数字.str() 中的每个元素,在 Count 迭代期间都存储在变量 s 中,如果它与 Sub(digit) 中的数字变量匹配> 会被统计

结果:

1 存在 42 存在 23 存在 10 存在 14 存在 1

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.

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