BURTON JOHN
BURTON JOHN

Reputation: 85

How to pull out just the duplicate values?

I have the following code that works well. In the last part of the code, for I=0 I was trying to add code that just displays the duplicate value only. I have a several listbox that do different things. I even have one that list the unique values but I cant figure out to get listbox8 to only display the dplicate values.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If GoLstBox.Items.Count <> 20 Then
        MessageBox.Show("Exactly Twenty Numbers Must Be Entered")
    Else
        Dim goArray(GoLstBox.Items.Count - 1) As Object
        GoLstBox.Items.CopyTo(goArray, 0)

        Array.Sort(goArray)
        ListBox6.Items.AddRange(goArray)

        Array.Reverse(goArray)
        ListBox5.Items.AddRange(goArray)

        Dim distinctNums = goArray.Distinct()
        Array.Sort(goArray)
        For Each num In distinctNums
            ListBox7.Items.Add(num.ToString())

            'For i = 0 To goArray.Count - 2
            'If goArray(i) = goArray(i + 1) Then
            ' ListBox8.Items(i + 1) = DirectCast(ListBox4.Items(i + 1), String))
        Next
    End If
End Sub

Upvotes: 0

Views: 62

Answers (1)

Moho
Moho

Reputation: 16498

Here's the algorithm you want in C# (as far as I can tell, anyway; your code/explanation isn't exactly crystal clear):

var groupedNumbers = goArray.GroupBy( n => n );

foreach( var numGroup in groupedNumbers )
{
    var num = numGroup.Key.ToString();

    ListBox7.Items.Add( num );

    if( numGroup.Count() > 1 )
    {
        ListBox8.Items.Add( num );
    }
}

Possible VB.Net translation (probably not 100% accurate but close enough):

    Dim groupedNumbers = goArray.GroupBy( Function( n ) n )

    For Each numGroup In groupedNumbers
        Dim num = numGroup.Key.ToString()

        ListBox7.Items.Add( num )

        If numGroup.Count() > 1 Then
            ListBox8.Items.Add( num )
        End If
    Next

Upvotes: 1

Related Questions