Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a structure that can be very easily represented using a three-deep nested dictionary, like so

private static Dictionary<string, Dictionary<string, Dictionary<string,string>>> PrerenderedTemplates;

Where the structure might be used something like this

PrerenderedTemplates[instanceID][templategroup][templatepart]

Now, I realise that this code is hard to read, because from looking at the definition statement, you can't tell what it's being used for. The only advantage I can really see in changing it to Dictionary<string, PrerenderedTemplate> is readability. Converting each nesting into its own class (e.g class PrerenderedTemplate{} class TemplateGroup{} class TemplatePart{}) would add many more lines of code for little (if any) computational advantage. As far as I can see.

  • So, is my approach "ok" or should I go the extra mile and create seperate classes?
  • Is it okay to cover how the nested Dictionary works in the documentation/comments
  • Is there a best practice for handling this sort of nesting?
  • Bear in mind, this is a private member, it doesn't need to be straightforward for people using the class.

Update

So, inspired by Reza, but unable to use Tuples, I decided to create my own key generator and implement his pattern like this:

private Dictionary<string, string> PrerenderedTemplates;
private string GetPrerenderedTemplateKey(string InstanceId, string FeatureId, string OptionId)
{
    return new StringBuilder(instanceId)
    .Append(FormatTools.LIST_ENTRY_DELIMITER)
    .Append(templategroup)
    .Append(FormatTools.LIST_ENTRY_DELIMITER)
    .Append(templatepart).ToString();
}

Where FormatTools.LIST_ENTRY_DELIMITER is the Unicode Private Use Character 0xe04d.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

I offer another choice:

Dictionary<Tuple<string, string, string>, string> pt;

Access to dictionary:

pt[Tuple.Create("id","group","part")]

UPDATE:

Value Tuples introduced in C# 7 is most eye-catching:

Dictionary<(string id, string group, string part), string> pt;

Access to dictionary:

pt[("id", "group", "part")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...