如何在 vb.net 中的字符串数组中查找和计算重复数字? [英] how to Find and count duplicate numbers in a string array in vb.net?

查看:137
本文介绍了如何在 vb.net 中的字符串数组中查找和计算重复数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何统计vb.net中字符串或整数数组中存在的重复数字?

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

<块引用>

从上面的a"变量中,我想要将3"计数为 2(我的意思是 3 存在 2 次),将2"计数为1".那么我如何在 vb.net 中制作它??????

实际上我会从sql数据库中得到上面的字符串a".所以我不知道那里有哪些数字.这就是我在这里问的原因.

解决方案

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

模块 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

这篇关于如何在 vb.net 中的字符串数组中查找和计算重复数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆