Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何在vb.net中查找和计算字符串数组中的重复数字?_Arrays_Vb.net - Fatal编程技术网

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

Arrays 如何在vb.net中查找和计算字符串数组中的重复数字?,arrays,vb.net,Arrays,Vb.net,如何计算vb.net中字符串或整数数组中存在的重复数 Dim a as string = "3,2,3" 从上面的“a”变量中,我希望计数“3”为2(我的意思是3存在2次),计数“2”为“1”。那么如何在vb.net中实现它呢 实际上,我将从sql数据库中获取上面的字符串“a”。所以我不知道有哪些数字。这就是我在这里问的原因 Dim count2 as integer = 0 Dim count3 as integer = 0 For Each c As Char in a if c

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

Dim a as string = "3,2,3"
从上面的“a”变量中,我希望计数“3”为2(我的意思是3存在2次),计数“2”为“1”。那么如何在vb.net中实现它呢

实际上,我将从sql数据库中获取上面的字符串“a”。所以我不知道有哪些数字。这就是我在这里问的原因

Dim count2 as integer = 0
Dim count3 as integer = 0    
For Each c As Char in a
 if c = "3"
      count3 += 1
 else if c = "2"
      count2 += 1
 end if
Next
console.writeline(count2)
console.writeline(count3)

我猜,如果你有一个像你例子中那样的字符串,那听起来有点像家庭作业,首先根据你的分隔符将它拆分;然后可以使用GroupBy Linq查询:

Dim source = "3,2,3".Split(","c)

Dim query = From item In source
            Group By item Into Count()

For Each result In query
    Console.WriteLine (result)
Next

' output
' { item = 3, Count = 2 }
' { item = 2, Count = 1 }
另一个选项使用:

输出:

Value: 3, Count: 2
Value: 2, Count: 1

您已经有了一些很好的答案可供选择,但我认为您会对单行程序解决方案感兴趣

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
关于发生了什么的解释:

  • str.
    -返回数组中所有唯一项的
    IEnumerable
    对象
  • -将
    IEnumerable
    对象转换为
    列表
  • -遍历
    列表
    • 子(数字)
      -定义要对每个元素执行的委托。在每次迭代中,每个元素都被命名为digit
    • 您应该知道Console.WriteLine()正在做什么
    • str.
      -将每次出现一个满足条件的数字进行计数
      • Function(s)s=digit
        -定义一个委托,该委托将对数组中每次出现的数字进行计数。在计数迭代期间,
        str()
        中的每个元素都存储在变量
        s
        中,如果它与
        Sub(digit)
        中的数字变量匹配,则将对其进行计数
结果:

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

如图所示,
a
是一个字符串,而不是字符串数组。但是有没有办法找到它的数量@你也在寻找最短的代码吗:-)@Shar1er80肯定…)我更喜欢你的回答,假设字符串代表数据,数字之间会有逗号
1 exists 4
2 exists 2
3 exists 1
0 exists 1
4 exists 1