Results 1 to 7 of 7

Thread: Visual Basic .NET - Which Collection Should I Use?

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Visual Basic .NET - Which Collection Should I Use?

    Common Theme
    Which collection should I use to store my values?

    Solution
    The solution that I am going to provide you with is not the final solution and is designed to be a best practices or highly encouraged suggestion.

    Frequently Asked Questions
    Question 1. I have a set of values and I know how many there are. No more values will be added and none of the existing values will be removed. What collection should I use?

    Answer: Use an array. Arrays are fixed sized collections and are highly efficient if you do not need to add or remove values. The following is a code snippet showing how arrays are used:
    Code:
    Dim initializedArray() As Integer = {1, 2, 3}
    
    Dim uboundsArray(2) As Integer
    uboundsArray(0) = 1
    uboundsArray(1) = 2
    uboundsArray(2) = 3
    Question2. I have a set of values and I need to have the opportunity to add new values or remove existing values, however I need to be able to add/remove items from any index within the collection. Which collection should I use?

    Answer: Use a List(Of T). Lists allow you to add/remove items at any index within the collection. The following is a code snippet showing how Lists are used:
    Code:
    Dim values As New List(Of Integer)
    values.Add(1)
    values.AddRange({1, 2, 3})
    values.RemoveAt(1)
    values.Insert(2, 88)
    Question3. I have a set of values and I need to have the opportunity to add new values or remove existing values, however I want the new values to be added at the end of the collection and the existing values to be removed from the start of the collection. Which collection should I use?

    Answer: Use a Queue(Of T). Queues represent a FIFO(first-in-first-out) collection which allow you to add new values to the end of the collection and remove existing values from the start of the collection. The following is a code snippet showing how Queues are used:
    Code:
    Dim values As New Queue(Of Integer)({1, 2, 3})
    values.Dequeue()
    values.Dequeue()
    values.Enqueue(4)
    values.Enqueue(5)
    Question4. I have a set of values and I need to have the opportunity to add new values or remove existing values, however I want the new values to be added at the end of the collection and the existing values to be removed from the end of the collection. Which collection should I use?

    Answer: Use a Stack(Of T). Stacks represent a LIFO(last-in-first-out) collection which allows you to add new values to the end of a collection and remove existing values from the end of the collection. The following is a code snippet showing how Stacks are used:
    Code:
    Dim values As New Stack(Of Integer)({1, 2, 3})
    values.Pop()
    values.Pop()
    values.Push(4)
    values.Push(5)
    Question5. I have a set of values that are pairs and I need to have the opportunity to add new values or remove existing values, however the one value in the pair needs to be unique. Which collection should I use?

    Answer: Use a Dictionary(Of TKey, TValue). Dictionaries represent a collection that stores key/value pairs where the key is a unique value. The following is a code snippet showing how Dictionaries are used:
    Code:
    Dim values As New Dictionary(Of Integer, String)
    values.Add(1, "a")
    values.Add(2, "b")
    values.Add(3, "c")
    Question6. I have a set of values that are pairs, however I don't want either the key or value in the pair to have to be unique. Which collection should I use?

    Answer: Create a custom class to hold your key/value pairs and store them in either an array, a list, a queue, or a stack depending on what you need to do with the collection.

    Question7. I have a set of values and I need to have the opportunity to add new values or remove existing values, however I need to be able to add/remove items from any index within the collection. To make things more complicated I am targeting a .NET framework that does not support List(Of T). Which collection should I use?

    Answer: You will still need to use an Array, however you will need to implement the ReDim Preserve operation. ReDim Preserve will redeclare the array while resizing the collection to a new size at the same time preserving the existing values. The following is a code snippet showing how ReDim Preserve is used:
    Code:
    Dim initializedArray() As Integer = {1, 2, 3, 4, 5}
    ReDim Preserve initializedArray(initializedArray.Length - 3)
    Last edited by dday9; May 11th, 2016 at 11:07 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  2. #2
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    354

    Re: Visual Basic .NET - Which Collection Should I Use?

    Simply, You know what? Gonna visit VB.NET FAQs subforum more often...

  3. #3
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,382

    Re: Visual Basic .NET - Which Collection Should I Use?

    Quote Originally Posted by dday9 View Post
    Answer: You will still need to use an Array, however you will need to implement the ReDim Preserve operation. ReDim Preserve will redeclare the array while resizing the collection to a new size at the same time preserving the existing values. The following is a code snippet showing how ReDim Preserve is used:
    Code:
    Dim initializedArray() As Integer = {1, 2, 3, 4, 5}
    ReDim Preserve initializedArray(initializedArray.Length - 3)
    No idea about .NET, but i remember from vb6, that ReDim Preserve was "expensive" (because you're throwing Data around in Memory)
    Is that still the case with .NET?

    in vba/vb6 i usually use a "overdimensioned" Array while keeping count of the non-empty members
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Visual Basic .NET - Which Collection Should I Use?

    Quote Originally Posted by Zvoni View Post
    No idea about .NET, but i remember from vb6, that ReDim Preserve was "expensive" (because you're throwing Data around in Memory)
    Is that still the case with .NET?

    in vba/vb6 i usually use a "overdimensioned" Array while keeping count of the non-empty members
    The best practice in .Net is to use a List(Of T). There is no reason whatsoever to ever use Redim Preserve in a VB.Net application. The only reason it even exists is to help ease the transition of VB6 programmers to VB.Net. A List(Of T) is a generic type which might completely startle a VB6 programmer who has never heard of generics before. Redim Preserve gives him something to fall back to until he is ready to step out of his comfort zone.

    The List(Of T) itself uses an array internally that doubles in size every time it overflows. So let's say it starts with a capacity of 10, when you add an 11th item, it will first create a new array that has a capacity of 20, it will copy the 10 items from the old array, add the new item and finally destroy the old array. The new array now becomes the backing store of the List. The List(Of T) class also provides a constructor for specifying and initially capacity so lets say you're sure that there will never be anymore than 200 items, you could start with an initial capacity of 200 to ensure that no resizing will occur as long as there are 200 or less elements.

    Also, bear in mind that this behavior is transparent to the developer so if you have a List with a capacity of 200 but only 25 items have been added to the List, you will only see 25 items if you For...Each or For...Next over it. It will throw an exception if you try to access the 26th item despite the fact that it technically has a 26th item since the internal array is 200 elements in size. This approach delivers optimized performance for element allocation and growth, surpassing traditional arrays, while also maintaining array-like behavior.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  5. #5

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    Re: Visual Basic .NET - Which Collection Should I Use?

    Quote Originally Posted by Zvoni View Post
    No idea about .NET, but i remember from vb6, that ReDim Preserve was "expensive" (because you're throwing Data around in Memory)
    Is that still the case with .NET?
    Yes, that is still the case. The List(Of T) was not introduced until the .NET framework 2.0 so I included it in the FAQ just in case.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  6. #6
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,598

    Re: Visual Basic .NET - Which Collection Should I Use?

    Quote Originally Posted by dday9 View Post
    Yes, that is still the case. The List(Of T) was not introduced until the .NET framework 2.0 so I included it in the FAQ just in case.
    There was the ArrayList class before the List(Of T) was introduced. It works the same way except for the fact that it was non-generic. It was could contain Integers and Strings at the same time and it was less performant due to all the boxing that would happen with primitive types like Integers and Doubles. This is why it was superseded by the List(Of T). The List(Of T) offered type safety and performance the ArrayList didn't.

    I would also note in this case that Redim Preserve may have been preferable to ArrayLists since arrays were as close to generics as one could come in the pre-generic era of .Net. You could use it to implement your own resizable List that avoids the penalty of boxing and offers the safety of strong typing.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

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

    Re: Visual Basic .NET - Which Collection Should I Use?

    Quote Originally Posted by Niya View Post
    it was less performant due to all the boxing that would happen with primitive types like Integers and Doubles.
    Quote Originally Posted by Niya View Post
    I would also note in this case that Redim Preserve may have been preferable to ArrayLists since arrays were as close to generics as one could come in the pre-generic era of .Net
    That is a massive understatement, an ArrayList could often be 2 or 3 times slower on reading / modifying small capacities, while in the order of 8 times slower on larger capacities. In most cases it was faster to just redim an array.
    Last edited by PlausiblyDamp; Mar 7th, 2023 at 04:47 PM.

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