Should i use a generic Dictionary or a Collection?

Hi. When i was using VB6 i was using collections.

Now, i tried to use the Dictionary in .net, as it is basically a strongly typed collection. When i used collections, everytime you added an object / key, it was given an index. I would for / next through the collection to get all of the objects.

How can i do this with a dictionary


Answer this question

Should i use a generic Dictionary or a Collection?

  • gon10289

    A List(Of T) can only be indexed with an integer, a Dictionary(Of K, V) can have any type (K) as the indexer. It really depends on your application which one you need. To get all the items in a collection, you can use For Each and iterate over the items (List) or the keys (Dictionary):



    Dim c As New List(Of String)

    c.AddRange(New String() {"Hello", "World", "foo", "bar"})

    Console.WriteLine(c(2)) ' returns foo

    For Each s As String In c

    Console.WriteLine(s)

    Next

    Dim d As New Dictionary(Of String, Integer)

    d.Add("foo", 42)

    Console.WriteLine(d("foo")) ' returns 42

    For Each s As String In d.Keys

    Console.WriteLine(d(s))

    Next



     






  • Should i use a generic Dictionary or a Collection?