基本上我有一个大小不同的整数数组。我需要将每个数字相互比较,并显示哪个数字是重复的。例如:
Dim ints() As Integer = {1,2,2,5,4,6}出现多次的数字是2。
如何遍历数组并将每个整数与数组中的数字进行比较。我尝试了一个for循环,但是它没有返回我想要的值。我是VB.NET的新手,不能完全理解。
发布于 2012-02-02 21:55:45
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这段代码的作用是:
发布于 2012-02-02 21:50:08
我会用下面这样的方式来尝试:
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在排序数组上这样做可以减少嵌套。
我没有对此进行测试,但它应该是正确的。
发布于 2012-02-02 21:50:46
您可以使用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)))https://stackoverflow.com/questions/9113354
复制相似问题