2014-04-08 93 views
1

我需要爲數組生成隨機(整數)元素列表,然後顯示唯一值。獲取隨機元素很簡單:識別VB數組中的重複項

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

私人小組btnAdd_Click(發送者爲對象,E作爲EventArgs的)把手btnAdd.Click

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

好了,現在我已經在另一個列表框中顯示任何/所有值不重複,所以首先我必須確定重複項。這就是我卡住的地方.....這個解決方案必須在新手級別,否則你會失去我。

+0

使用LINQ擴展方法:'Dim uniques = numbers.Distinct()。ToArray()'。 – Styxxy

+1

@Styxxy:'Distinct'方法不會刪除具有重複項的值,它只會刪除重複項並留下每個值之一。 – Guffa

回答

1

可以組上的值,並含有一個以上的項目組數組是重複的:

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

我很抱歉,但是這是超過新手水平...我不明白任何它... – user3500004

0

我認爲LINQ,通過@Guffa爲指向,是完成這一任務的最便捷的方式任務。但您也可以使用基本的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())) 
+0

好吧,我想我遵循這個...但我怎麼才能獲得獨特的價值觀到一個新的列表框? – user3500004

+0

使用LINQ獲取唯一值:'Dim unique = numbers.Except(duplicates).Distinct()'。下一步是什麼?如何在ListBox中顯示'unique'? – har07