Arraylist duplication string removal

suresh_ed

Active member
Joined
May 19, 2008
Messages
27
Programming Experience
1-3
I have a arraylist which contains more than 50 strings like this:

Somename#P#10.
Somename1#P#10.
Somename2#P#10.
Somename#P#10.


I have to match the string before # i.e., somename; with each and every other string. If a match found i have to delete the string from the arraylist.
 
If a match found i have to delete the string from the arraylist.
I'm assuming that you're wanting only unique strings to be in the ArrayList.
VB.NET:
Public Class Form1
    Dim MyArray As New ArrayList

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MyArray.AddRange(New String() {"Somename#P#10.", "Somename1#P#10.", "Somename2#P#10.", "Somename#P#10."})
        For Counter1 As Integer = MyArray.Count - 1I To 1I Step -1I
            For Counter2 As Integer = Counter1 - 1I To 0I Step -1I
                If CStr(MyArray(Counter1)).Substring(0I, CStr(MyArray(Counter1)).IndexOf("#"c)) = CStr(MyArray(Counter2)).Substring(0I, CStr(MyArray(Counter2)).IndexOf("#"c)) Then
                    MyArray.RemoveAt(Counter1)
                    Exit For
                End If
            Next Counter2
        Next Counter1
        ListBox1.Items.AddRange(MyArray.ToArray)
    End Sub
End Class
There is a ListBox on the form as well to display the results
 
Assuming the same, that you want only items with unique first part, here's an example using a HashTable:
VB.NET:
Dim hash As New Hashtable
For Each item As String In list
    Dim key As String = item.Remove(item.IndexOf("#"c))
    If Not hash.ContainsKey(key) Then
        hash.Add(key, item)
    End If
Next
You can then get the unique items from the hash.Values collection.
 
VB.NET:
        'm_MyArray as ArrayList declared elsewhere

        Dim intDupIndex As Integer = -1
        Dim intIndex As Integer = 0

        'Loop thru each ArrayList item
        For intIndex = 0 To m_MyArray.Count - 1

            'Loop thru until all dupes of this item are removed
            Do While intIndex < m_MyArray.Count - 1

                'Search for duplicates past the current index item
                intDupIndex = m_MyArray.IndexOf(m_MyArray(intIndex), intIndex + 1)

                If intDupIndex > 0 Then
                    'Remove Dup
                    m_MyArray.RemoveAt(intDupIndex)
                Else
                    'Go to next ArrayList Item
                     Continue For
                End If
            Loop

        Next intIndex
 
Last edited:
Back
Top