是否有基于元组或嵌套的字典有什么好处? [英] Is there a benefit to Tuple-based or Nested Dictionaries?

查看:140
本文介绍了是否有基于元组或嵌套的字典有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方式来存储和比单密钥的C#泛型类Dictionary提供了更多的检索值。

I've been looking for a way to store and retrieve values on more than the single key that C#'s generic Dictionary class provides.

搜索网络上(< A HREF =htt​​p://stackoverflow.com/questions/2877660/composite-key-dictionary>和SO本身)已经表明了我一对夫妇的选择:

Searching around the web (and on SO itself) has shown me a couple options:

基于元组的字典

.NET 4.0可以轻松地支持通用的元组LT;,>类。这意味着你可以做一个字典出任意元组,即

.NET 4.0 makes it easy to support a generic Tuple<,> class. This means you can make a Dictionary out of any arbitrary Tuple, i.e.,


  • VAR myDict =新词典<元组LT ;字符,诠释>中MyClass的>();

  • var myDict = new Dictionary<Tuple<Char, Int>, MyClass>();

嵌套字典

我已经学会了,你也可以字典中嵌套字典,这使得访问类似于访问一个多维数组中所存储的结果。例如:

I've learned you can also nest Dictionaries within Dictionaries, which makes accessing the stored result similar to accessing an N-Dimensional array. For instance:

Dictionary<int, Dictionary<int, Dictionary<Char, MyClass>>>



这可能然后被accsessed: MyClass的富=迈德特[8] [ 3] ['W'];

分隔的级联密钥字典

不过,虽然两者的工作的以及复杂的数据和自定义类,我不知道如果他们总是必要的。对于原始数据,至少,它似乎是一个分隔符串联键一样有效。

But while both work well for complex data and custom classes, I wonder if they're always necessary. For primitive data, at least, it would seem that concatenating the keys with a delimiter is just as effective.

//keys are char + int
Dictionary<string, MyClass> myDict = New Dictionary<string, Myclass>();
String input = myChar + "|" + myInt
MyClass foo = myDict[input]



有没有这使得中的任何一个场景这些方法优于其他?他们将有类似的表现时间?还是应该把重点放在而不是在该方法提供了干净,容易维护,代码?

Are there any scenarios which make one of these methods superior to the other? Will they have similar performance times? Or should the focus be instead on which method provides the cleanest, easiest to maintain, code?

思考?

推荐答案

分隔的级联密钥字典

有至少有三个原因,我会避免这种方法:

There are at least three reasons why I would avoid this approach:


  • 这是魔术。有没有在告诉你如何构建它,或者它代表了什么键的类型。

  • 如果分隔符偶然出现的一个值,你的做法会失败。

  • 转换为字符串,并且这些字符串的比较可能是(略)高于使用两个基本类型的慢。

嵌套字典

这解决了分隔符的问题,而是引入了一些新的问题:

This solves the problem with the delimiter, but introduce some new problems:


  • 新的价值观的插入比较困难,因为每个嵌套的水平,你必须检查键是否已经存在。如果没有,你需要创建一个新的字典作为值。这使得使用字典更加困难。

  • 将有进一步的存储器和性能开销。

基于元组的字典

您发布的办法,这可能是最好的。

Of the approaches you posted, this is probably the best.

但是,你可以把它一步,创建一个名为不变结构为您的钥匙。这将使你的字典更容易使用,因为关键的部位可以有有用的名称。

But you could take it one step further and create a named immutable struct for your key. This will make your dictionary easier to use because the parts of the key can have useful names.

这篇关于是否有基于元组或嵌套的字典有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆