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
    12,089

    Visual Basic .NET - Which Collection Should I Use?

    Common Theme

    Which collection should I use to store my values? This guide will help you choose the appropriate VB.NET collection based on your specific needs.

    Solution

    The recommendations below provide best practices to help you select the right collection for your data. These are suggestions, and in some cases, you may need to modify based on your specific scenario.

    Array - Fixed Size Collection

    Question: I have a fixed set of values, and I know the exact number. No more values will be added or removed. What collection should I use?
    Answer: Use an Array. Arrays are fixed-size collections that are highly efficient when you don’t need to modify the number of elements.
    Example:
    Code:
    Dim initializedArray() As Integer = {1, 2, 3}
    Dim fixedArray(2) As Integer
    fixedArray(0) = 1
    fixedArray(1) = 2
    fixedArray(2) = 3
    Documentation: https://learn.microsoft.com/en-us/do...atures/arrays/

    List(Of T) - Flexible, Indexed Collection

    Question: I need to add or remove values, and I want the flexibility to do this at any position within the collection. What collection should I use?
    Answer: Use a List(Of T). Lists allow dynamic resizing and let you insert or remove items at any index.
    Example:
    Code:
    Dim values As New List(Of Integer)
    values.Add(1)
    values.AddRange({1, 2, 3})
    values.RemoveAt(1)
    values.Insert(2, 88)
    Documentation: https://learn.microsoft.com/en-us/do...generic.list-1

    Queue(Of T) - First-In-First-Out Collection

    Question: I need to add values to the end of the collection and remove values from the start, following a "first-in, first-out" rule. What collection should I use?
    Answer: Use a Queue(Of T). Queues work on a FIFO (first-in-first-out) principle, allowing additions at the end and removals from the beginning.
    Example:
    Code:
    Dim values As New Queue(Of Integer)({1, 2, 3})
    values.Dequeue()
    values.Enqueue(4)
    values.Enqueue(5)
    Documentation: https://learn.microsoft.com/en-us/do...eneric.queue-1

    Stack(Of T) - Last-In-First-Out Collection

    Question: I need to add values to the end of the collection and remove values from the end, following a "last-in, first-out" rule. What collection should I use?
    Answer: Use a Stack(Of T). Stacks follow a LIFO (last-in-first-out) model, where the last item added is the first one removed.
    Example:
    Code:
    Dim values As New Stack(Of Integer)({1, 2, 3})
    values.Pop()
    values.Push(4)
    Documentation: https://learn.microsoft.com/en-us/do...eneric.stack-1

    HashSet(Of T) - Storing Unique Values

    Question: I have a collection of values, and I need to ensure that every value is unique. What collection should I use?
    Answer: Use a HashSet(Of T). A HashSet(Of T) is ideal when you need to store a unique set of elements. It does not allow duplicate values, and the order of elements is not guaranteed.
    Example:
    Code:
    Dim uniqueValues As New HashSet(Of Integer)
    uniqueValues.Add(1)
    uniqueValues.Add(2)
    uniqueValues.Add(2) 'This will not be added again
    uniqueValues.Add(3)
    Documentation: Documentation: https://learn.microsoft.com/en-us/do...eric.hashset-1

    Dictionary(Of TKey, TValue) - Key/Value Pairs with Unique Keys

    Question: I need to store pairs of values where one part of the pair must be unique. What collection should I use?
    Answer: Use a Dictionary(Of TKey, TValue). Dictionaries store key/value pairs where the key must be unique.
    Example:
    Code:
    Dim values As New Dictionary(Of Integer, String)
    values.Add(1, "a")
    values.Add(2, "b")
    values.Add(3, "c")
    Documentation: https://learn.microsoft.com/en-us/do...c.dictionary-2

    Custom Class for Key/Value Pairs without Unique Keys

    Question: I need to store pairs of values, but neither value needs to be unique. What collection should I use?
    Answer: Create a custom class to store key/value pairs, and use an array, list, queue, or stack depending on how you need to access the collection. For example, if you want flexibility to add or remove items at any position, use a List(Of T).

    Array with ReDim Preserve - Dynamic Sizing without List(Of T)

    Question: I need to add or remove values at any position within the collection, but I'm targeting a .NET framework version that does not support List(Of T). What should I use?
    Answer: Use an Array and employ the ReDim Preserve operation to resize the array while maintaining its existing values.
    Example:
    Code:
    Dim initializedArray() As Integer = {1, 2, 3, 4, 5}
    ReDim Preserve initializedArray(initializedArray.Length - 1)
    Documentation: https://learn.microsoft.com/en-us/do...edim-statement
    Last edited by dday9; Sep 27th, 2024 at 08:39 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
    384

    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
    5,027

    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,798

    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
    12,089

    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,798

    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,855

    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