vb.net 包含字符串数组作为值的字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19272521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:25:04  来源:igfitidea点击:

Dictionary containing an array of strings as value

vb.net

提问by Kasper Hansen

Is it possible to have a string array as the value in a dictionary? I need to save the description (Hour2) as the key and as value being able to access both the price (elements_PR(4)) and the time offset (1). Is there a good way to do that?

是否可以将字符串数组作为字典中的值?我需要将描述 (Hour2) 保存为能够访问价格 (elements_PR(4)) 和时间偏移 (1) 的键和值。有没有好的方法可以做到这一点?

Dim pr_val(2) As String
Dim PR As New Dictionary(Of String, pr_val)

PR.Add("Hour2", {elements_PR(4), "1"})

回答by staafl

There is no reason why you can't do it - you could also use values of type Tuple(Of String, String), if the number of elements is fixed in advance - in this case, 2. It'd be easier to perform comparisons on, and would also be immutable, which is often a good idea.

没有理由你不能这样做——你也可以使用 Tuple(Of String, String) 类型的值,如果元素的数量是预先固定的——在这种情况下,2.它会更容易执行比较,并且也是不可变的,这通常是一个好主意。

回答by Douglas Barbin

You sure can. Try something like this:

你肯定可以。尝试这样的事情:

Dim PR As New Dictionary(Of String, IEnumerable(Of String))
PR.Add("Hour2", {elements_PR(4), "1"})

回答by Benjamin Beaulieu

It seems to me that you could create a class representing the price and the time offset. Therefore, you could do something like PR.Add("Hour2", instanceOfClass).

在我看来,您可以创建一个表示价格和时间偏移的类。因此,你可以做类似的事情PR.Add("Hour2", instanceOfClass)

Depending on the meaning of the description in your situation, you could even include it in your class. It would allow you to use another approach with a List(Of YourClass)containing a list of items with the description, the price and the time offset. To retrieve an item by "key", you could then use some Linq.

根据您的情况描述的含义,您甚至可以将其包含在您的班级中。它将允许您使用另一种方法,其中List(Of YourClass)包含带有描述、价格和时间偏移的项目列表。要通过“键”检索项目,您可以使用一些 Linq。

回答by Neolisk

Short answer - yes. Assuming the following was declared somewhere:

简短的回答 - 是的。假设在某处声明了以下内容:

Dim elements_PR(4) As String : elements_PR(4) = "Hello"
Dim PR As New Dictionary(Of String, String())

You can either do:

你可以这样做:

PR.Add("Hour2", {elements_PR(4), "1"})

or

或者

Dim pr_val() As String = {elements_PR(4), "1"}
PR.Add("Hour1", pr_val)