基本上我有大小不一的整数数组。我需要将每个数字与每个数字进行比较,并显示重复的数字。例如:
Dim ints() As Integer = {1,2,2,5,4,6}
不止一次出现的数字是2。
如何运行数组并将每个整数与数组中的数字进行比较。我试过一个for循环,但它没有返回我想要的值。我是VB.NET的新手,并不完全理解。
答案 0 :(得分:1)
Dim ints() As Integer = {1,2,2,5,4,6}
Dim repeatedNumbers = ints.GroupBy(Function(intValue) intValue) _
.Where(Function(grp) grp.Count > 1)
For each grp in repeatedNumbers
Console.WriteLine("Number {0} is repeated {1} times", grp(0), grp.Count)
Next
此代码的作用:
答案 1 :(得分:0)
我会尝试这样的事情:
Dim ints() As Integer = {1, 2, 2, 5, 4, 6}
Array.Sort(ints)
For i = 1 To ints.GetUpperBound(0)
If ints(i) = ints(i - 1) Then MessageBox.Show(String.Format("{0} is repeated", ints(i)))
Next
在排序数组上执行此操作会使嵌套保持不变。
我没有测试过这个,但它应该是正确的。
答案 2 :(得分:0)
您可以使用LINQ查找重复项:
Dim repeating = (From n In ints
Group By n Into Dups = Group
Where Dups.Count > 1
Select Dups.First).ToArray()
这将返回一个整数数组,该数组仅包含原始数组中不唯一的数字。
这样就显示了重复的数字:
MessageBox.Show(String.Format("Duplicates found: {0}", String.Join(","c, repeating)))