识别VB数组中的重复项

时间:2014-04-08 22:00:43

标签: arrays vb.net duplicates

我需要为数组生成随机(整数)元素列表,然后显示唯一值。获取随机元素很简单:

Dim ro As New Random
Dim numbers(19) As Integer
Dim counter As Integer

Private Sub btnAdd_Click(sender as Object,e As EventArgs)处理btnAdd.Click

  numbers(counter) = ro.Next(10, 101)
  lstNumEntered.Items.Add(numbers(counter))
  counter += 1

好的,现在我必须在另一个列表框中显示任何/所有非重复的值,所以首先我必须识别重复项。这就是我被困的地方.....这个解决方案必须是新手级别,否则你会失去我。

2 个答案:

答案 0 :(得分:1)

您可以对数组进行分组,包含多个项目的组是重复项:

Dim duplicates As List(Of Integer) = _
  numbers.GroupBy(Function(n) n) _
  .Where(Function(g) g.Count() > 1) _
  .Select(Function(g) g.First) _
  .ToList()

答案 1 :(得分:0)

我认为@Guffa指出的LINQ是完成此任务最方便的方法。但您也可以使用基本For循环操作来完成此操作。

有一个临时集合来存储不同的值(在下面的示例中为distinct),然后在每个For循环迭代中,如果遇到该集合中已存在的数字,则确切地知道该数字是重复的:

'variable to store distinct numbers (either duplicated or not)
Dim distinct As New List(Of Integer)
'variable to store duplicated numbers
Dim duplicates As New List(Of Integer)

For i As Integer = 0 To numbers.Length - 1
    'if distinct doesn't contain number(i), means this number isn't duplicated SO FAR
    If Not distinct.Contains(numbers(i)) Then
        distinct.Add(numbers(i))
    'else, means distinct already contains the number, means this numbers(i) is a DUPLICATE
    'if the number hasn't been added to duplicates, add it
    ElseIf Not duplicates.Contains(numbers(i)) Then
        duplicates.Add(numbers(i))
    End If
Next

'following lines are for debugging purpose only
'print all numbers
Console.WriteLine(String.Join(",", numbers.Select(Function(x) x.ToString()).ToArray()))
'print all duplicates
Console.WriteLine(String.Join(",", duplicates.Select(Function(x) x.ToString()).ToArray()))
'print distinct numbers
Console.WriteLine(String.Join(",", distinct.Select(Function(x) x.ToString()).ToArray()))