分享

VB.NetDictionary的技巧和8个实例

 孙无者 2020-06-11

1. Adding keys

First, nearly every program that uses Dictionary in VB.NET will require the Add subroutine. The Add subroutine requires two arguments in its parameter list, the first being the key of the element to add, and the second being the value that key should have. Internally, the Add subroutine computes the key's hash code value, and then stores the data in the hash bucket. Because of this step, adding to Dictionary collections is slower than adding to other collections like List.

~~~ Program that uses Dictionary Of String (VB.NET) ~~~

Module Module1

    Sub Main()

        Dim dictionary As New Dictionary(Of String, Integer)

        dictionary.Add('Dot', 20)

        dictionary.Add('Net', 1)

        dictionary.Add('Perls', 10)

        dictionary.Add('Visual', -1)

    End Sub

End Module

~~~ Results of program ~~~

    The Dictionary has four keys and values.

Using Add subroutine. The program above will succeed without an exception. However, if you add keys to the Dictionary and one of the keys is already in the Dictionary, you will get an exception. If it is possible the key already exists, always check with ContainsKey that the key is not present. Alternatively, you can catch possible exceptions with Try and Catch.

2. Using ContainsKey

Here we look at the ContainsKey function on the Dictionary generic collection in the VB.NET language. The ContainsKey function returns a Boolean value, which means you can use it in an If conditional statement. One common use of ContainsKey is to prevent exceptions before calling Add. Another use is simply to see if the key exists in the hash table, before you take further action.

--- Program that uses ContainsKey (VB.NET) ---

Module Module1

    Sub Main()

        ' Declare new Dictionary with String keys.

        Dim dictionary As New Dictionary(Of String, Integer)

        ' Add two keys.

        dictionary.Add('carrot', 7)

        dictionary.Add('perl', 15)

        ' See if this key exists.

        If dictionary.ContainsKey('carrot') Then

            ' Write value of the key.

            Dim num As Integer = dictionary.Item('carrot')

            Console.WriteLine(num)

        End If

        ' See if this key also exists (it doesn't).

        If dictionary.ContainsKey('python') Then

            Console.WriteLine(False)

        End If

    End Sub

End Module

--- Results of program ---

7

Using ContainsKey Function. This function in the base class library on the Dictionary type returns a Boolean value. If the key was found in the Dictionary, it returns True; if the key was not found, it returns False. You can also store the result of ContainsKey in a Dim Boolean, and test that variable with the = and <> binary operators.

Using Item Function. The Item member is actually a Property accessor, which allows you to set or get an element in the Dictionary. It is equivalent to Add when you assign it. You can assign it to a nonexistent key, but you cannot access a nonexistent key with Item without an exception. [TODO - Add to other article]

3. Looping over keys and values

Here we look at how you can loop over the entries in your Dictionary using the VB.NET language. It is usually easiest to use the For Each iterative statement to loop over the KeyValuePair structures in the Dictionary. In the body of the For Each loop, you can access the KeyValuePair's Key and Value get accessors. They have the types of the Dictionary keys and values so no casting is required.

=== Program that loops over entries (VB.NET) ===

Module Module1

    Sub Main()

        ' Put four keys into a Dictionary Of String.

        Dim dictionary As New Dictionary(Of String, Integer)

        dictionary.Add('please', 32)

        dictionary.Add('help', 16)

        dictionary.Add('program', 256)

        dictionary.Add('computers', -1)

        ' Loop over entries.

        Dim pair As KeyValuePair(Of String, Integer)

        For Each pair In dictionary

            ' Display Key and Value.

            Console.WriteLine('{0}, {1}', pair.Key, pair.Value)

        Next

    End Sub

End Module

=== Output of the program ===

please, 32

help, 16

program, 256

computers, -1

Understanding KeyValuePair. In the base class library, the KeyValuePair type is implemented as a struct, which means it is used as a value and its contents are contains in the variable storage location itself. This can improve performance in some cases and cause slowdowns in other cases.

4. Getting keys List

Here we look at how you can get a List collection of the keys in a Dictionary using the VB.NET language. Every Dictionary instance has a get accessor property with the identifier Keys. You can access this collection, and pass it to a List constructor to obtain a List of the keys. The keys have the same type as that from the source Dictionary.

--- Program that gets List of keys (VB.NET) ---
 
Module Module1
    Sub Main()
        ' Put four keys and values in the Dictionary.
        Dim dictionary As New Dictionary(Of String, Integer)
        dictionary.Add('please', 12)
        dictionary.Add('help', 11)
        dictionary.Add('poor', 10)
        dictionary.Add('people', -11)
 
        ' Put keys into List Of String.
        Dim list As New List(Of String)(dictionary.Keys)
 
        ' Loop over each string.
        Dim str As String
        For Each str In list
            ' Print string and also Item(string), which is the value.
            Console.WriteLine('{0}, {1}', str, dictionary.Item(str))
        Next
    End Sub
End Module
 
--- Output of the program ---
 
please, 12
help, 11
poor, 10
people, -11

5. Using different key types

In the VB.NET language, the Dictionary collection can use any type as its key type and any type for its values. However, you must always specify these types when the Dictionary is declared. This next example doesn't use String keys; instead it uses Integer keys and String values.

~~~ Program that uses Integer keys (VB.NET) ~~~
 
Module Module1
    Sub Main()
        ' Put two Integer keys into Dictionary Of Integer.
        Dim dictionary As New Dictionary(Of Integer, String)
        dictionary.Add(100, 'Bill')
        dictionary.Add(200, 'Steve')
 
        ' See if this key exists.
        If dictionary.ContainsKey(200) Then
            ' Print value at this key.
            Console.WriteLine(True)
        End If
    End Sub
End Module
 
~~~ Output of the program ~~~
 
True

Using type parameters. The part of the program after 'New Dictionary', which contains the 'Of Integer, String' text, is where the types of the Dictionary instance are declared. The VB.NET compiler will disallow any other types being used as the keys or values. This can result in much higher quality in your code over using Hashtable.

6. Using ContainsValue

Here we look at the ContainsValue Public Function in a VB.NET program. This function returns a Boolean value that tells you whether any value in the Dictionary is equal to the argument you provide. In the base class library, this method is implemented as a For loop over the entries in the Dictionary. For this reason, it provides no performance advantage over a List collection that uses linear searching. Accessing keys in your Dictionary is much faster.

~~~ Program that uses ContainsValue (VB.NET) ~~~
 
Module Module1
    Sub Main()
        ' Create new Dictionary with Integer values.
        Dim dictionary As New Dictionary(Of String, Integer)
        dictionary.Add('pelican', 11)
        dictionary.Add('robin', 21)
 
        ' See if Dictionary contains the value 21 (it does).
        If dictionary.ContainsValue(21) Then
            ' Prints true.
            Console.WriteLine(True)
        End If
    End Sub
End Module
 
~~~ Output of the program ~~~
 
True

7. Removing keys and values

Here we look at an example of using the Remove function on the Dictionary type. You must pass one parameter to this method, indicating which key you want to have removed from the Dictionary instance. If you try to remove a key that does not exist in the Dictionary, no exceptions will be thrown.

=== Program that removes keys (VB.NET) ===
 
Module Module1
    Sub Main()
        ' Create Dictionary and add two keys.
        Dim dictionary As New Dictionary(Of String, Integer)
        dictionary.Add('fish', 32)
        dictionary.Add('microsoft', 23)
 
        ' Remove two keys.
        dictionary.Remove('fish')  ' Will remove this key.
        dictionary.Remove('apple') ' Doesn't change anything.
    End Sub
End Module

8. Using class-level Dictionary

In many programs, using Dictionary instances as local variables is not as useful as storing them as member variables at the class level. This is because they are often used for lookups more than they are used for adding elements. This example shows how you can store a Dictionary instance as Private member variable, and then access it through Public methods through the enclosing object.

~~~ Program that uses class Dictionary (VB.NET) ~~~
 
Module Module1
    ''' <summary>
    ''' Stores class-level Dictionary instance.
    ''' </summary>
    Class Example
 
        Private _dictionary
 
        Public Sub New()
            ' Allocate and populate the field Dictionary.
            Me._dictionary = New Dictionary(Of String, Integer)
            Me._dictionary.Add('make', 55)
            Me._dictionary.Add('model', 44)
            Me._dictionary.Add('color', 12)
        End Sub
 
        Public Function GetValue() As Integer
            ' Return value from private Dictionary.
            Return Me._dictionary.Item('make')
        End Function
 
    End Class
 
    Sub Main()
        ' Allocate an instance of the class.
        Dim example As New Example
 
        ' Write a value from the class.
        Console.WriteLine(example.GetValue())
    End Sub
End Module
 
~~~ Output of the program ~~~
 
55

Understanding reference types. In the VB.NET language, the Dictionary type is considered a reference type. This means it contains a reference or pointer to the actual data contained in the Dictionary. The actual data is stored in the managed heap, while the variable and the storage location is stored in the method's stack. For this reason, using Dictionary as a return type or Function parameter is very fast.

9. Exceptions

Many programs that use Dictionary instances extensively will run into the KeyNotFoundException when looking up values in Dictionary. To prevent these errors, you must always guard your accesses to Dictionary entries using the ContainsKey method, or the TryGetValue method. Using the Items property will result in this error commonly. [TODO - VB.NET TryGetValue Function]

10. Dictionary versus List performance

The Dictionary collection in the base class library for the .NET Framework is intended as an optimization for key lookups. It can make a slow program many times faster, making your chances of getting fired much smaller. However, in certain cases the Dictionary will reduce performance. This will occur on very small collections, and also when your program has to add keys much more often than look them up. The Dictionary must compute a hash code each time you add a key.

11. Counting keys

You can count the number of entries in your Dictionary in the VB.NET language by using the Count get accessor property. Internally, the Count property subtracts two integers. This means it is very fast and does not slow down even on huge Dictionary instances. You do not need to specify the parentheses after the Count property access.

12. Copying entire Dictionary

It is possibly to copy the entire contents of the Dictionary in VB.NET, not just the reference variable. You can do this by declaring a new Dictionary reference and using the copy constructor. In the Dictionary constructor, pass the Dictionary you want to copy as the parameter. The entire contents of the Dictionary are copied.

13. Summary

Here we saw many examples and tips for using the Dictionary type in the VB.NET programming language, targeting the .NET Framework. The Dictionary collection is extremely powerful and can greatly improve the performance of applications, and even make it simpler by checking for duplicates. We looked at adding keys, looping over entries, removing keys, looking up values, avoiding exceptions, and also explored several methods on Dictionary. [This article is based on the .NET Framework 3.5 SP1.]

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多