如何在 vb.net 中的字符串数组中查找和计算重复数字? [英] how to Find and count duplicate numbers in a string array in 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
结果:
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 anIEnumerable
object of all unique items in the array.
ToList() - Turns theIEnumerable
object into aList<T>
.
ForEach() - Iterates through theList<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 conditionFunction(s) s = digit
- Defines a Func delegate that will count each occurrence of digits in the array. Each element, instr()
, during the Count iterations are stored in the variables
and if it matches the digit variable fromSub(digit)
it will be counted
Results:
1 exists 4
2 exists 2
3 exists 1
0 exists 1
4 exists 1
这篇关于如何在 vb.net 中的字符串数组中查找和计算重复数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!