密钥值对数据结构的最佳实现?

Ber*_*ard 72 c# collections data-structures

所以我最近一直在讨论C#,所有的Generic Collections让我有些困惑.假设我想表示一个数据结构,其中树的头是一个键值对,然后在它下面有一个可选的键值对列表(但没有比这些更多的级别).这适合吗?

public class TokenTree
{
    public TokenTree()
    {
        /* I must admit to not fully understanding this,
         * I got it from msdn. As far as I can tell, IDictionary is an
         * interface, and Dictionary is the default implementation of
         * that interface, right?
         */
        SubPairs = new Dictionary<string, string>();
    }

    public string Key;
    public string Value;
    public IDictionary<string, string> SubPairs;
}
Run Code Online (Sandbox Code Playgroud)

传递数据只是一个简单的分流.

Ada*_*ile 135

有一个名为KeyValuePair的实际数据类型,就像这样使用

KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");
Run Code Online (Sandbox Code Playgroud)

  • KeyValuePair&lt;string, string&gt; NAME_HERE = new KeyValuePair&lt;string,string&gt;("defaultkey", "defaultvalue"); (8认同)

Jon*_*jap 12

你可以做的一件事就是直接使用Dictionary对象,然后用你自己的修改来扩展它:

public class TokenTree : Dictionary<string, string>
{
    public IDictionary<string, string> SubPairs;
}
Run Code Online (Sandbox Code Playgroud)

这使您无需为密钥强制执行IDictionary规则(例如,密钥唯一性等).

并且你明白了构造函数的概念:)


Sha*_*tin 7

我认为你可能会追求的(作为你的问题的字面实现)是:

public class TokenTree
{
    public TokenTree()
    {
        tree = new Dictionary<string, IDictionary<string,string>>();
    }

    IDictionary<string, IDictionary<string, string>> tree; 
}
Run Code Online (Sandbox Code Playgroud)

你确实在你的问题中说了一个关键值的"列表",所以你可能想要用以下内容交换内部IDictionary:

IList<KeyValuePair<string, string>>
Run Code Online (Sandbox Code Playgroud)


Coi*_*oin 5

有一个KeyValuePair内置类型.事实上,这是IDictionary在您迭代时可以访问的内容.

此外,这种结构几乎不是一棵树,找到一个更有代表性的名字可能是一个很好的锻炼.