VB.Net Dictionary的技巧和8个实例

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.]

复现基于混频因子模型的GDP即时预测方法 基于混频因子模型的GDP即时预测方法复现 本文复现了混频因子模型(MIDAS)在GDP即时预测中的应用。该方法整合7个月度宏观经济变量(工业增加值、CPI、PMI等)与季度GDP数据,通过状态空间模型实现高频预测。技术实现包括:1)使用PCA提取潜在共同因子;2)构建状态空间模型处理混频数据;3)通过卡尔曼滤波进行参数估计。实证结果显示模型预测效果良好(测试集R²=0.82),其中工业增加值对因子1贡献最大(0.82),CPI对因子2贡献显著(0.78)。该方法为决策者提供了更及时的季度GDP估算。 阅读详情

相关推荐

(一)企业微信 - 会话内容存档

企业微信获取会话记录。

专打丶小豆豆的博客 2913

vb.net 教程 1-13 Dictionary

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。 Dictionary 是表示根据键的哈希代码进行组织的键值对(Key/Value)的集合。 Dictionary类同HashTable类操作差不多,本节内容将用示例方式讲解Dictionary 增、删、改、枚举、查找操作。 设计窗口如下: 定义窗体级变量,注意Dictionary必须指定参数...

学习微软 .net 技术开发 8372

用Arduino和RC522模块DIY一个NFC门禁卡复制器(附完整代码)

本文详细介绍了如何利用Arduino和RC522模块DIY一个NFC门禁卡复制器,包括硬件连接、软件配置、数据读写技术及完整代码实现。通过本教程,电子爱好者可以深入了解NFC技术,并构建自己的智能门禁系统,适用于家庭安全、办公场所等多种场景。

weixin_33704591的博客 506

VB.NET中的字典及遍历

其中键是字符串类型,值是整数类型。它包含了三个键值对:Apple-10、Banana-20和Orange-30。字典作为VB.NET中的一种集合类型,它可以存储键值对:每个键必须是唯一的,而每个值可以是任何类型。字典可以用于快速查找和访问数据,因为它们使用哈希表来实现。在VB.NET中,字典可以通过使用Dictionary(Of TKey, TValue)类来创建。

weixin_44783823的博客 2733

COCOS 3.8 接入高德定位SDK

/微信登录所必须的code。//是否获得code。

八喜互动 1998

PCB测试点

PCB测试点

qq_31444421的博客 1万+

【Vb.net】字典(Dictionary)在VB.NET中的详细用法汇总 (VS2010

字典(Dictionary)是VB.NET中一种非常重要的集合类型,它存储键值对(key-value pairs),提供了基于键的快速查找功能。

weixin_43910833的博客 639

AI驱动芯片设计的端到端验证:AI应用架构师的全流程指南

想象你要建造一座1000层的超级摩天大楼,每个房间都有独特的功能,管道、电路、电梯系统交织如迷宫。传统的检查方式是派1000个工程师逐层逐房手动检查,耗时十年且仍可能遗漏火灾隐患。这就是今天芯片设计面临的困境:7nm芯片含百亿晶体管,相当于百亿个"房间",传统验证方法(人工编写测试用例、随机仿真)已难以应对。本文的目的,是为AI应用架构师提供一份"AI驱动芯片验证导航图",范围涵盖从验证需求分析到芯片签核的全流程,包括AI模型如何融入传统验证工具链、数据如何驱动验证效率提升、以及端到端闭环系统的构建方法。

2501_92132293的博客 1246

VB.NET 字典(Dictionary)的完整用法(deepseek)

【代码】VB.NET 字典(Dictionary)的完整用法(deepseek)

ssq9595的博客 888

Jetson AGX Orin平台Jetpack5升级Jetpack6,自研载板USB不工作问题调试

1. 问题描述将AGX Orin工业的新板放到定制的载板上当在ubuntu 22和Jetpack 6.1上使用SDKManager刷机时,lsusb为空,并且在引导时没有发现/注册xusb设备。USB C端口正常打开并供电,但似乎没有数据传输。在Ubuntu 18 Jetpack 5.1.4 SDKManager上同样刷机之后,usb C集线器在引导时被正确地发现,显示在lsusb中,并识别/挂载外部驱动器。

jzwjzw19900922的博客 1513

基于YOLO的智能视频监控异常行为检测研究:从算法原理到落地部署的全栈实践

本文深入探讨如何利用 YOLO(You Only Look Once)系列算法构建一套端到端的异常行为检测系统。文章首先回顾 YOLOv8 在时空建模上的局限,然后提出“YOLO-STA(Spatio-Temporal Aggregation)”轻量级改进框架,在公开数据集 UCF-Crime 上将异常行为检测的 mAP@0.5 从 72.4 提升到 80.1;接着给出完整训练、推理、部署的 Python 代码(PyTorch + TensorRT),并介绍如何仅用 4 GB 显存的 Jetson Xavi

博客 1397

[VB.NET]Dictionary类

字典类是一个很重要的类,尤其是对于数据的简单存储,查询,和处理。 废话不多说,简单记录下我探索的结果。 1、 Dictionary内部索引是0基的。也就是说第一个元素的序号是0. 2、 1 Public Class DictionaryTryMain 2 3 Private Sub btnClassBase_Click(ByVal sender As Sy...

weixin_34198881的博客 1034

Kimodo 入门教程(一)英伟达开源人形机器人动捕数据集训练运动学动作扩散模型

Kimodo是一个基于700小时商用光学动作捕捉数据集训练的运动学动作扩散模型,能够生成高质量的人体和机器人3D动作。该模型支持通过文本提示和多种约束条件(如关键帧、末端执行器位置等)进行控制,并提供数字人类和类人机器人两种模型变体。安装方式包括软件包安装和源代码安装两种,需要配置HuggingFace令牌以访问文本编码器。推荐使用GPU加速,最低需要17GB显存。项目提供命令行生成和交互式演示两种使用方式,演示程序支持时间轴编辑和实时3D可视化。模型分为商用友好版和受限版,其中SMPL-X版本需要额外申请

2506_90492529的博客 1967

dictionary-字典用法 VB.net 2005

 Dim stateCaps As New Dictionary(Of String, String)        ' Add items to the dictionary        stateCaps.Add("WA", "Olympia")        stateCaps.Add("NM", "Santa Fe")        Trace.WriteLine(stateCaps.Item("WA"))  'True        Trace.WriteLine(statecaps.Conta

ckp00001的专栏 5771

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

vb.net 教程 1-14 Hashtable 和 Dictionary比较

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。 Hashtable 和 Dictionary 都是一个键值对的集合 其中 Hashtable 包含的单个键值对为 DictionaryEntry 结构 Dictionary 包含的单个键值对为 KeyValuePair 结构 共同点: 1、都只能有唯一的键(Key),如果要增加同样的键会报错,...

学习微软 .net 技术开发 2236

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

C# 与vb.net 的Dictionary(字典)的键、值排序

原文地址VB和VB.NET的大致区别_copico的博客-CSDN博客_vbnet和vb的语法区别Visual Basic .NET是Microsoft Visual Studio .NET套件中主要组成部分之一。.NET版本的Visual Basic增加了更多特性,而且演化为完全面向对象(就像C++)的编程语言。本文将介绍VB.NET的新特性,并比较VB6.0/VB.NET之间的区别,阐述如何利用V

chinaherolts2008的博客 1507

VB.NET 中的2种集合

//在  .NET种又2种集合 一种是 VB的 collection   集合 另一种是   .NET Framework 的泛型集合   ////VB的collection集合     和 .NET下的泛型集合 泛型集合限定了 键值对的类型 1.   VB的collect

Programmer小卫 8191

.net - Microsoft.VisualBasic.Collection 和 .NET System.Collections.Generic.Dictionary(Of TKey, TValue

我正在为费城的一家贸易公司做一个相当大的项目。该公司利用自动交易算法处理流式报价并每秒数十次发送数百种产品的报价。显然,性能是一个重要的问题。 (这让我怀疑为什么我们使用 VB.NET,但这完全是另一个话题。) 我对公司相对较新,正在与另一个人一起研究一些已经存在了一段时间的代码。此代码利用 Microsoft.VisualBasic.Collection 对象来存储所有产品(代表成对的 ETF 或股票的对象以及关于每个产品的大量数据),并从该集合中进行大量搜索/检索。 据我了解,Collection 类.

jkipweyjj的博客 374

VB.Net学习笔记之VB.Net基础

VB.net的基础知识以及在开发中常用的知识点总结

weixin_40822435的博客 730

vb.net 教程 6-9 传值给线程1

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。 Thread类的Start方法可以启动线程,同时还可以传一个值给线程: '声明 Public Sub Start ( _ parameter As Object _ ) 所传的值是Object类型,对应调用的方法中需要增加一个Object参数。 以下代码中sample4_Prin...

学习微软 .net 技术开发 1387

VB.NET编程入门与实战技巧

VB.NET作为.NET框架下的面向对象编程语言,继承了经典VB的易读性特点,同时具备完整的面向对象特性。其编译生成的中间语言(IL)与C#具有相同的运行时性能,特别适合Windows窗体应用、数据库系统和Office自动化等场景开发。通过Visual Studio提供的强大IDE支持,开发者可以快速构建企业级应用。本文重点解析VB.NET的核心语法、数据库连接、异步编程等关键技术,并分享实际项目中的性能优化和异常处理经验,帮助开发者掌握从基础到进阶的VB.NET开发技能。

weixin_33924220的博客 387

给VB.NET开发者的46个忠告

1、把VB.NET当成一门新的语言学习(和VB6没啥关系,真的); 2、看一些VB.NET的高级教程,不要因为他们很难而我们自己是初学者所以就不看; 3、不要放过任何一个看上去很简单的小编程问题——他们往往并不那么简单,或者可以引伸出很多知识点; 4、会用VB6,并不说明你会VB.NET; 5、学Class并不难,XML IO、Dictionary、SOAP也不过如此——难的是长期坚持实践和不遗余...

cs_wxd的博客 5323

字典在VBA与VB.NET的区别,举例说明

在VBA中,字典通常使用Scripting.Dictionary对象,通过CreateObject("Scripting.Dictionary")创建。在VB.NET中,字典使用泛型集合Dictionary(Of TKey, TValue),属于System.Collections.Generic命名空间。VB.NET字典具有更丰富的功能,如ContainsKey、ContainsValue等方法。例如:在VBA中检查键是否存在用Exists,而在VB.NET中用ContainsKey。

fsyuheduo的博客 1203

【VB.NET】Dictionary按Value进行排序

VB.NET ' sortbyvalue.vb Imports System Imports System.Net Imports System.Text.RegularExpressions Imports System.Collections.Generic Class DictionarySortByValue   Shared Sub makeDict(ByVal d...

weixin_34334744的博客 891

Dictionary序列化

VB.NET Imports System Imports System.Collections.Generic Imports System.Runtime.Serialization Imports System.Xml Imports System.Xml.Schema Imports System.Xml.Serialization ''' ''' 支持XML序列化的字典

Chobits的专栏 1219

C#中Dictionary(字典)的用法

在C#中,Dictionary提供快速的基于兼职的元素查找。他的结构是这样的:Dictionary<[key], [value]> ,当你有很多元素的时候可以使用它。它包含在System.Collections.Generic名空间中。在使用前,你必须声明它的键类型和值类型。 方法/步骤 要使用Dictionary集合,需要导入C#泛型命名空间 System...

Peter的博客 9861
上一篇: VB读取EXCEL
下一篇: VB中的Dictionary对象
tdsys
博客等级 码龄16年 1粉丝 1原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值