Results 1 to 21 of 21

Thread: [RESOLVED] Resizing Array in VB.NET

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Resolved [RESOLVED] Resizing Array in VB.NET

    Hello,

    I have set up a little test as I need an Array to be updated with values from another Array.

    When I monitor AddToArray all seems to go well, but after I run TestArray, I expect MainArray to have 3 new elements and it doesn't.
    What am I missing?

    Code:
        Dim MainArray() As Object = {"Hello World", 12D, 16UI, "A"c, "blob"}
        Dim AdditionalArray() As Object = {"carriage", 200, "Friend"}
    
        Sub TestArray()
            Dim i As Integer
            AddToArray(MainArray, AdditionalArray)      ' UBound of MainArray was 7 in TestArray
    
            MsgBox("Ubound MA = " & UBound(MainArray))  ' here UBound of MainArray is 4 again
            For i = LBound(MainArray) To UBound(MainArray)
                MsgBox(i & ": " & MainArray(i))
            Next
        End Sub
    
        Sub AddToArray(MainArray As Object, AdditionalArray As Object)
            Dim i As Long
            MsgBox("Initial UBound MA = " & UBound(MainArray))
            For i = LBound(AdditionalArray) To UBound(AdditionalArray)
                ReDim Preserve MainArray(UBound(MainArray) + 1)
                MsgBox("New UBound MA = " & UBound(MainArray))
                MainArray(UBound(MainArray)) = AdditionalArray(i)
            Next
            MsgBox("Final UBound MA = " & UBound(MainArray))
        End Sub

  2. #2
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,958

    Re: Resizing Array in VB.NET

    VB provides a Concat method for arrays as part of Linq you should be able to use something like
    Code:
          MainArray = MainArray.Concat(AdditionalArray).ToArray
    to combine the two arrays into a single array.

    However you might find something like a List(Of ...) might make life easier as Lists are designed to grown and shrink without the issues associated with arrays.

    More of an issue though is why are you creating an array that is mixing completely different data types in that way? If you could give an exampel of what you are trying to achieve as your end result there might be a better way that doesn't involve arrays.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Thumbs up Re: Resizing Array in VB.NET

    Quote Originally Posted by PlausiblyDamp View Post
    VB provides a Concat method for arrays as part of Linq you should be able to use something like
    Code:
          MainArray = MainArray.Concat(AdditionalArray).ToArray
    to combine the two arrays into a single array.

    However you might find something like a List(Of ...) might make life easier as Lists are designed to grown and shrink without the issues associated with arrays.

    More of an issue though is why are you creating an array that is mixing completely different data types in that way? If you could give an exampel of what you are trying to achieve as your end result there might be a better way that doesn't involve arrays.
    ThanX PlausiblyDamp,

    MainArray = MainArray.Concat(AdditionalArray).ToArray does the trick! I wish we had had that one in VBA ;-)

    The reason why I make an array of mixed objects is only "because I can" since Dim MainArray() As Object permits us to do that.


  4. #4
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: Resizing Array in VB.NET

    You might find that using List is easier to work with.

    Code:
            Dim MainArray As New List(Of Object)
            Dim initA() As Object = {"Hello World", 12D, 16UI, "A"c, "blob"}
            MainArray.AddRange(initA)
    
            Dim AdditionalArray() As Object = {"carriage", 200, "Friend"}
            MainArray.AddRange(AdditionalArray)
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  5. #5
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,958

    Re: Resizing Array in VB.NET

    Quote Originally Posted by BartH_NL View Post
    ThanX PlausiblyDamp,

    MainArray = MainArray.Concat(AdditionalArray).ToArray does the trick! I wish we had had that one in VBA ;-)

    The reason why I make an array of mixed objects is only "because I can" since Dim MainArray() As Object permits us to do that.

    Just because you can doesn't always mean you should if this is any kind of real application mixing data types like that is going to almost certainly hurt you down the line - it makes it impossible to access any array element safely without wrapping every access in type checks and / or error handling.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Resizing Array in VB.NET

    That looks like VB6 code, not .NET. If you are going to use .NET, one rule you might as well keep in mind is that if you EVER write Redim Preserve, you're doing it wrong. If you write Redim...you might be doing it wrong, but Redim Preserve is right out.

    Arrays can't change size. Sure, you have Redim to set a size, but that doesn't change the size of the array. It creates a new array of the new size. If you have the Preserve word in there, then it copies the data from the old array to the new array. Either way, in the end, the old array is thrown out. That last step isn't so costly, because nothing is likely to happen at the moment. However, getting those new arrays is costly. There's a best way to do that, which has been understood for decades, and Redim ain't it. Therefore, the List was added to .NET back in 2005 (and before that was the ArrayList, which is essentially like a List(of Object)) so that you wouldn't have to deal with that. The List has .Add, Insert, Remove, and RemoveAt methods, along with many more. These allow you to add and remove items to and from the list however you need to. It does wrap an array, and that array is no more sizable than any other array, but it will resize in a very efficient fashion. Therefore, it is like using Redim Preserve, except better in every way, so Redim Preserve shouldn't be used.

    If you're wondering what it does, it doubles the size of the array every time it needs to. Thus, if your array starts off with 16 elements, as soon as you add the 17th element, the array doubles to 32 elements, so you can add the 17th through 32nd. Once you add the 33rd element, it doubles again to 64 elements, and so forth. This means that the most costly step, that of acquiring the memory happens as infrequently as possible.

    So, use a List unless your arrays will never change size.

    Also, arrays in .NET don't have variable lower bounds. They start at 0, and only at 0. The upper bound can be obtained in a variety of ways, too, so the UBound command, while still around, is an anachronism. Since all arrays start at 0, the upper bound is the length minus one, and can't be anything other than that. That's true for Lists as well as arrays, since Lists wrap arrays. Therefore, you can dispense with LBound in all cases, and UBound if you want to.
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    Quote Originally Posted by PlausiblyDamp View Post
    Just because you can doesn't always mean you should if this is any kind of real application mixing data types like that is going to almost certainly hurt you down the line - it makes it impossible to access any array element safely without wrapping every access in type checks and / or error handling.
    Yep PlausiblyDamp, ThnX, I get that. I certainly will use string or integer if that is more applicable than object.

  8. #8

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    Quote Originally Posted by dbasnett View Post
    You might find that using List is easier to work with.

    Code:
            Dim MainArray As New List(Of Object)
            Dim initA() As Object = {"Hello World", 12D, 16UI, "A"c, "blob"}
            MainArray.AddRange(initA)
    
            Dim AdditionalArray() As Object = {"carriage", 200, "Friend"}
            MainArray.AddRange(AdditionalArray)
    ThnX dbasnett, that looks very usable. I'll look into that. .AddRange is very handy here.

  9. #9

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    Hi Shaggy Hiker,

    That is indeed where I come from: VBA, VBS and VB6 ;-) ThnX for the clear explanation. I'll use that.

  10. #10
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,958

    Re: Resizing Array in VB.NET

    Quote Originally Posted by BartH_NL View Post
    Yep PlausiblyDamp, ThnX, I get that. I certainly will use string or integer if that is more applicable than object.
    The problem really is the fact you are mixing data types in a single array, that is always going to make having proper data types difficult. Is there a real reason why you need to mix datatypes in an array in this fashion?

  11. #11
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Resizing Array in VB.NET

    The lower bound of arrays and lists is zero in VB.Net as Shaggy told you. The exact .Net replacement for UBound is the GetUpperBound(dimension) extension function.
    For example...

    Code:
    Dim a() As String = {"one", "two", "three"}
    MsgBox(a.GetUpperBound(0)) ' returns 2
    Which is equivalent to...

    Code:
    Dim a() As String = {"one", "two", "three"}
    MsgBox(UBound(a)) ' returns 2

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Resizing Array in VB.NET

    Quote Originally Posted by .paul. View Post
    The exact .Net replacement for UBound is the GetUpperBound(dimension) extension function.
    It's not an extension. It's an instance method of the Array class. That means that it is only available for arrays, not collections. That makes sense, given that it requires a dimension to be specified. Arrays can have multiple dimensions while collections cannot.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Resizing Array in VB.NET

    Quote Originally Posted by jmcilhinney View Post
    It's not an extension. It's an instance method of the Array class. That means that it is only available for arrays, not collections. That makes sense, given that it requires a dimension to be specified. Arrays can have multiple dimensions while collections cannot.
    I knew it wasn’t to be used with Lists. I didn’t intend to imply it could be used with Lists, though I can see the ambiguity...

  14. #14
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Resizing Array in VB.NET

    Quote Originally Posted by .paul. View Post
    I knew it wasn’t to be used with Lists. I didn’t intend to imply it could be used with Lists, though I can see the ambiguity...
    I'm not sure that there are any standard extension methods that work on arrays but nothing else. The centre of LINQ is the IEnumerable(Of T) interface and that is what methods written to support LINQ originally extended, hence their being members of the Enumerable class. Obviously extension methods have grown in popularity well beyond LINQ but I'm still not aware of anything standard that works solely on arrays. I may just have missed it though.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  15. #15

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    @PlausiblyDamp
    No, I don't need to mix data types, I was only interested to see how they could be mixed.
    What I am really trying to do is to select only the images in a folder and collect them for display in a form.
    I have found that I can collect the FileInfo (for which I would need the Object type in the previous example) or the FilePath (which is obviously String).
    That's why I came to Object in Array.

  16. #16
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,958

    Re: Resizing Array in VB.NET

    Quote Originally Posted by BartH_NL View Post
    @PlausiblyDamp
    No, I don't need to mix data types, I was only interested to see how they could be mixed.
    What I am really trying to do is to select only the images in a folder and collect them for display in a form.
    I have found that I can collect the FileInfo (for which I would need the Object type in the previous example) or the FilePath (which is obviously String).
    That's why I came to Object in Array.
    You can declare an Array of Type FileInfo - there is no need to use Object if you know the datatype. Then agani it would probably be easier to work with a List(Of FileInfo) rather than an array as SH mentioned earlier.

  17. #17

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    Quote Originally Posted by PlausiblyDamp View Post
    You can declare an Array of Type FileInfo - there is no need to use Object if you know the datatype. Then agani it would probably be easier to work with a List(Of FileInfo) rather than an array as SH mentioned earlier.
    Well PlausiblyDamp,

    I got to this now:

    Code:
        Private Sub FilesCollect(StrPath$)
            Dim i As Long
            Dim MyExtensions As New List(Of String)({"*.jpg", "*.jpeg", "*.png", "*.gif", "*.tiff", "*.bmp", "*.svg"})
    
            FileList.Clear()
            For Each F In MyExtensions
                Dim files() As FileInfo = New DirectoryInfo(StrPath).GetFiles(F)
                For i = 0 To files.GetUpperBound(0)
                    FileList.Add(files(i))
                Next
            Next
        End Sub
    and that is a whole lot less code than what I had before.

    ThanX for pointing that out to me.

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Resizing Array in VB.NET

    Code:
        Private Sub FilesCollect(StrPath$)
            Dim MyExtensions = {"*.jpg", "*.jpeg", "*.png", "*.gif", "*.tiff", "*.bmp", "*.svg"}
            Dim folder As New DirectoryInfo(StrPath)
    
            FileList.Clear()
    
            For Each F In MyExtensions
                FileList.AddRange(folder.GetFiles(F))
            Next
        End Sub
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Resizing Array in VB.NET

    @jm I’m fairly sure that can be done in one line with LINQ. Which was (just) available in VB2008

  20. #20
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Resizing Array in VB.NET

    Quote Originally Posted by .paul. View Post
    @jm I’m fairly sure that can be done in one line with LINQ. Which was (just) available in VB2008
    A SelectMany would do the job, but that might be a bit much for the OP at this stage.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  21. #21

    Thread Starter
    Junior Member
    Join Date
    Feb 2020
    Posts
    22

    Re: Resizing Array in VB.NET

    Quote Originally Posted by jmcilhinney View Post
    Code:
        Private Sub FilesCollect(StrPath$)
            Dim MyExtensions = {"*.jpg", "*.jpeg", "*.png", "*.gif", "*.tiff", "*.bmp", "*.svg"}
            Dim folder As New DirectoryInfo(StrPath)
    
            FileList.Clear()
    
            For Each F In MyExtensions
                FileList.AddRange(folder.GetFiles(F))
            Next
        End Sub
    Neat!!!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width