41

I create a dictionary

    Dim ImageCollection As New Dictionary(Of ConvensionImages, Integer)

and I fill that

 For Each dr As DataRow In dt.Rows
            Dim obj As New ConvensionImages
            obj.ImageID = dr("ID")
            obj.Name = dr("Name")
            obj.Description = dr("Description")
            obj.CategoryID = dr("CategoryID")
            obj.CategoryName = dr("CategoryName")
            obj.CategoryDescription = dr("CatDescription")
            obj.EventID = dr("EventID")
            obj.Image = dr("img")
            obj.DownloadImage = dr("DownLoadImg")
            ImageCollection.Add(obj, key)
            key = key + 1

now I want to search ImageID and key how can I do this

2 Answers 2

78

Make Integer as key for your Dictionary:

Dim ImageCollection As New Dictionary(Of Integer, ConvensionImages)

Change ImageCollection.Add(obj, key) to ImageCollection.Add(key, obj)

And use this loop:

For Each kvp As KeyValuePair(Of Integer, ConvensionImages) In ImageCollection
     Dim v1 As Integer = kvp.Key  
     Dim v2 As ConvensionImages = kvp.Value  
     'Do whatever you want with v2:
     'If v2.ImageID = .... Then
Next  
1
  • 1
    You should change the definition of the KeyValuePair in the loop to (Of Integer, ConvensionImages)
    – Heslacher
    Sep 5, 2013 at 6:34
20

You can loop this way, too:

For Each iKey As Integer In ImageCollection.Keys
    Dim value As ConvensionImages = ImageCollection(iKey)
    '...
Next

It is very fast and simple way to it.

3
  • 3
    It may not be so fast. Inside the loop your are searching for the key in the dictionary for every iteration. You should use something like for each pair in ImageCollection and use pair.Value inside the loop Nov 22, 2017 at 12:36
  • that is done on the other answer, this is to provide an alternative.
    – SysDragon
    Aug 6, 2018 at 6:26
  • 2
    If you consider @Emanuele Benedetti's comment, also consider: "Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table." source
    – Chris
    Apr 16, 2021 at 17:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.