Unique String Array in vb.net

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paulers

    #1

    Unique String Array in vb.net

    Hello all,

    I have a string array with duplicate elements. I need to create a new
    string array containing only the unique elements. Is there an easy way
    to do this? I have tried looping through each element but I am having
    issues using redim to adjust the new array. Any help or example code
    would be greatly appreciated. thanks!

  • _AnonCoward

    #2
    Re: Unique String Array in vb.net


    "Paulers" <SuperGh0d@gmai l.com> wrote in message
    news:1139467217 .227961.95350@g 47g2000cwa.goog legroups.com...
    :
    : Hello all,
    :
    : I have a string array with duplicate elements. I need to create a new
    : string array containing only the unique elements. Is there an easy way
    : to do this? I have tried looping through each element but I am having
    : issues using redim to adjust the new array. Any help or example code
    : would be greatly appreciated. thanks!


    Arrays are fixed length and generally are best used when you know in advance
    (or can easily calculate) how large it needs to be and if you are not going
    to be changing the size of the array frequently (if at all).

    For your purposes here, try using the ArrayList object instead (see
    namespace System.Collecti ons). You can dynamically add strings (or any
    object for that matter) to the array without having to concern yourself with
    the hassles and performance issues associated with redimensioning regular
    arrays.

    Here is a quick example (VB.NET 2.0):

    '************** *************** *************** **********
    Option Strict

    Imports Microsoft.Visua lBasic
    Imports System
    Imports System.Collecti ons

    Public Module MyModule

    Public Sub Main

    Dim S1(10) As String
    Dim S2() As String
    Dim AR As New ArrayList
    Dim ndx As Integer

    'Create a string array with duplicate entries for entries
    '"Item 1", "Item 2" and "Item 6"
    s1(0) = "Item 1"
    s1(1) = "Item 3"
    s1(2) = "Item 2"
    s1(3) = "Item 4"
    s1(4) = "Item 1"
    s1(5) = "Item 2"
    s1(6) = "Item 6"
    s1(7) = "Item 5"
    s1(8) = "Item 6"
    s1(9) = "Item 2"
    s1(10) = "Item 1"

    'Display the contents of S1
    DumpArray(S1, "Contents of S1()")

    'Load only unique values to an array list object
    For ndx = 0 To 10
    If Not Ar.Contains(S1( ndx)) Then
    Ar.Add(S1(ndx))
    End If
    Next

    'Go ahead and sort this array list just for grins and giggles
    Ar.Sort

    'Turn this back into an array
    ReDim S2(Ar.Count - 1)
    For ndx = 0 To Ar.Count - 1
    S2(ndx) = CType(Ar.Item(n dx), String)
    Next

    'Now let's print out the contents of array S2
    DumpArray(S2, "Contents of S2()")

    End Sub

    Private Sub DumpArray(S() As String, msg As String)
    Dim ndx As Integer

    Console.WriteLi ne(msg)
    Console.WriteLi ne("--------------------------------------")
    For ndx = 0 to UBound(S)
    Console.WriteLi ne(S(ndx))
    Next
    Console.WriteLi ne
    End Sub

    End Module
    '************** *************** *************** **********


    This will produce the following output:

    Contents of S1()
    --------------------------------------
    Item 1
    Item 3
    Item 2
    Item 4
    Item 1
    Item 2
    Item 6
    Item 5
    Item 6
    Item 2
    Item 1

    Contents of S2()
    --------------------------------------
    Item 1
    Item 2
    Item 3
    Item 4
    Item 5
    Item 6


    Please notice a few things about this code.

    1 - I did not define the size of S2 at first since I didn't know going in
    what size it would be when the process was complete


    2 - I didn't assign an initial value to the ArrayList object either. I just
    added objects as needed and it handled all that work


    3 - I was able to easily avoid duplicate entries by using the .Contains
    method of the ArrayList.


    4 - The original array was not sorted but the final array was. All I needed
    was a simple one-line statement to achieve this: AR.Sort


    5 - The ArrayList stored everything as an Object. When I get those objects
    back out of the ArrayList, I have to recast them as String objects (using
    the CType keyword)


    6 - I was able to correctly size array S2 when I finally reached that point
    by referencing the .Count property of the ArrayList. There was no need for
    me to track that myself.


    HTH


    Ralf
    --
    ----------------------------------------------------------
    * ^~^ ^~^ *
    * _ {~ ~} {~ ~} _ *
    * /_``>*< >*<''_\ *
    * (\--_)++) (++(_--/) *
    ----------------------------------------------------------
    There are no advanced students in Aikido - there are only
    competent beginners. There are no advanced techniques -
    only the correct application of basic principles.


    Comment

    • Cor Ligthert [MVP]

      #3
      Re: Unique String Array in vb.net

      Paulers,

      I am in doubt if I had seen one simple method from Herfried, however as long
      as he has not answered.

      Why not Split the string, sort the resulting array, and than remove via one
      of the classic methods for that the duplicates.

      Cor


      Comment

      • Herfried K. Wagner [MVP]

        #4
        Re: Unique String Array in vb.net

        "Paulers" <SuperGh0d@gmai l.com> schrieb:[color=blue]
        > I have a string array with duplicate elements. I need to create a new
        > string array containing only the unique elements. Is there an easy way
        > to do this? I have tried looping through each element but I am having
        > issues using redim to adjust the new array.[/color]

        <URL:http://groups.google.d e/group/microsoft.publi c.dotnet.langua ges.vb/msg/5b636776cb33d1c d>

        --
        M S Herfried K. Wagner
        M V P <URL:http://dotnet.mvps.org/>
        V B <URL:http://classicvb.org/petition/>

        Comment

        • Mythran

          #5
          Re: Unique String Array in vb.net


          "_AnonCowar d" <abcdef@uvwxyz. com> wrote in message
          news:QmCGf.1143 2$915.4717@sout heast.rr.com...[color=blue]
          >
          > "Paulers" <SuperGh0d@gmai l.com> wrote in message
          > news:1139467217 .227961.95350@g 47g2000cwa.goog legroups.com...
          > :
          > : Hello all,
          > :
          > : I have a string array with duplicate elements. I need to create a new
          > : string array containing only the unique elements. Is there an easy way
          > : to do this? I have tried looping through each element but I am having
          > : issues using redim to adjust the new array. Any help or example code
          > : would be greatly appreciated. thanks!
          >
          >
          > Arrays are fixed length and generally are best used when you know in
          > advance
          > (or can easily calculate) how large it needs to be and if you are not
          > going
          > to be changing the size of the array frequently (if at all).
          >
          > For your purposes here, try using the ArrayList object instead (see
          > namespace System.Collecti ons). You can dynamically add strings (or any
          > object for that matter) to the array without having to concern yourself
          > with
          > the hassles and performance issues associated with redimensioning regular
          > arrays.
          >
          > Here is a quick example (VB.NET 2.0):
          >
          > '************** *************** *************** **********
          > Option Strict
          >
          > Imports Microsoft.Visua lBasic
          > Imports System
          > Imports System.Collecti ons
          >
          > Public Module MyModule
          >
          > Public Sub Main
          >
          > Dim S1(10) As String
          > Dim S2() As String
          > Dim AR As New ArrayList
          > Dim ndx As Integer
          >
          > 'Create a string array with duplicate entries for entries
          > '"Item 1", "Item 2" and "Item 6"
          > s1(0) = "Item 1"
          > s1(1) = "Item 3"
          > s1(2) = "Item 2"
          > s1(3) = "Item 4"
          > s1(4) = "Item 1"
          > s1(5) = "Item 2"
          > s1(6) = "Item 6"
          > s1(7) = "Item 5"
          > s1(8) = "Item 6"
          > s1(9) = "Item 2"
          > s1(10) = "Item 1"
          >
          > 'Display the contents of S1
          > DumpArray(S1, "Contents of S1()")
          >
          > 'Load only unique values to an array list object
          > For ndx = 0 To 10
          > If Not Ar.Contains(S1( ndx)) Then
          > Ar.Add(S1(ndx))
          > End If
          > Next
          >
          > 'Go ahead and sort this array list just for grins and giggles
          > Ar.Sort
          >
          > 'Turn this back into an array
          > ReDim S2(Ar.Count - 1)
          > For ndx = 0 To Ar.Count - 1
          > S2(ndx) = CType(Ar.Item(n dx), String)
          > Next
          >
          > 'Now let's print out the contents of array S2
          > DumpArray(S2, "Contents of S2()")
          >
          > End Sub
          >
          > Private Sub DumpArray(S() As String, msg As String)
          > Dim ndx As Integer
          >
          > Console.WriteLi ne(msg)
          > Console.WriteLi ne("--------------------------------------")
          > For ndx = 0 to UBound(S)
          > Console.WriteLi ne(S(ndx))
          > Next
          > Console.WriteLi ne
          > End Sub
          >
          > End Module
          > '************** *************** *************** **********
          >
          >
          > This will produce the following output:
          >
          > Contents of S1()
          > --------------------------------------
          > Item 1
          > Item 3
          > Item 2
          > Item 4
          > Item 1
          > Item 2
          > Item 6
          > Item 5
          > Item 6
          > Item 2
          > Item 1
          >
          > Contents of S2()
          > --------------------------------------
          > Item 1
          > Item 2
          > Item 3
          > Item 4
          > Item 5
          > Item 6
          >
          >
          > Please notice a few things about this code.
          >
          > 1 - I did not define the size of S2 at first since I didn't know going in
          > what size it would be when the process was complete
          >
          >
          > 2 - I didn't assign an initial value to the ArrayList object either. I
          > just
          > added objects as needed and it handled all that work
          >
          >
          > 3 - I was able to easily avoid duplicate entries by using the .Contains
          > method of the ArrayList.
          >
          >
          > 4 - The original array was not sorted but the final array was. All I
          > needed
          > was a simple one-line statement to achieve this: AR.Sort
          >
          >
          > 5 - The ArrayList stored everything as an Object. When I get those objects
          > back out of the ArrayList, I have to recast them as String objects (using
          > the CType keyword)
          >
          >
          > 6 - I was able to correctly size array S2 when I finally reached that
          > point
          > by referencing the .Count property of the ArrayList. There was no need for
          > me to track that myself.
          >
          >
          > HTH
          >
          >
          > Ralf
          > --
          > ----------------------------------------------------------
          > * ^~^ ^~^ *
          > * _ {~ ~} {~ ~} _ *
          > * /_``>*< >*<''_\ *
          > * (\--_)++) (++(_--/) *
          > ----------------------------------------------------------
          > There are no advanced students in Aikido - there are only
          > competent beginners. There are no advanced techniques -
          > only the correct application of basic principles.
          >
          >[/color]

          Nice reply...but for dealing with strings, I would use the
          System.Collecti ons.Specialized .StringCollecti on collection instead of the
          ArrayList since this is what it was created for (a collection of strings).

          Mythran

          Comment

          • _AnonCoward

            #6
            Re: Unique String Array in vb.net


            "Mythran" <kip_potter@hot mail.comREMOVET RAIL> wrote in message
            news:%23WsHekZL GHA.2904@TK2MSF TNGP10.phx.gbl. ..
            :
            : "_AnonCowar d" <abcdef@uvwxyz. com> wrote in message
            : news:QmCGf.1143 2$915.4717@sout heast.rr.com...
            : >
            : > "Paulers" <SuperGh0d@gmai l.com> wrote in message
            : > news:1139467217 .227961.95350@g 47g2000cwa.goog legroups.com...
            : > :
            : > : Hello all,
            : > :
            : > : I have a string array with duplicate elements. I need to create a new
            : > : string array containing only the unique elements. Is there an easy way
            : > : to do this? I have tried looping through each element but I am having
            : > : issues using redim to adjust the new array. Any help or example code
            : > : would be greatly appreciated. thanks!


            <snip>


            : Nice reply...but for dealing with strings, I would use the
            : System.Collecti ons.Specialized .StringCollecti on collection instead of the
            : ArrayList since this is what it was created for (a collection of strings).
            :
            : Mythran


            Agreed. I didn't think of that class when I wrote my response. Hopefully the
            OP has enough information to achieve his/her objectives. Thanx,


            Ralf
            --
            --
            ----------------------------------------------------------
            * ^~^ ^~^ *
            * _ {~ ~} {~ ~} _ *
            * /_``>*< >*<''_\ *
            * (\--_)++) (++(_--/) *
            ----------------------------------------------------------
            There are no advanced students in Aikido - there are only
            competent beginners. There are no advanced techniques -
            only the correct application of basic principles.


            Comment

            Working...