tags:

views:

46

answers:

3

Hi Guys.

I created a complex dictionary.

mainDict<mainKey, SubDict>
subDict<subKey, sub1Dict>
sub1Dict<sub1Key, sub2Dict>
sub2Dict<sub2Key, sub2Value>
.......

How to print it out like this (vs2005 & .net 2.0 based)

mainKey/subKey/sub1Key/sub2Key, sub2Value

Do i need convert mainDict to a List and call join()?

thank you.

+2  A: 

Can't see anything much better than nested loops for this - iterate over mainDict's keys, then subDict's keys inside that, and so on. You can then render the loop variables and the innermost value as a string.

David M
+1  A: 

You can use LINQ:

var qry = from pair1 in mainDict
          from pair2 in pair1.Value
          from pair3 in pair2.Value
          from pair4 in pair3.Value
          select pair1.Key + "/" + pair2.Key + "/" + pair3.Key
                   + "/" + pair4.Key + ", " + pair4.Value;

foreach(var s in qry) Console.WriteLine(s);
Marc Gravell
Nano HE
Then I see a lot of nested loops in your future...
Marc Gravell
For info, if you had VS2008 you can still use LINQ-to-Objects with .NET 2.0 via LINQBridge: http://www.albahari.com/nutshell/linqbridge.aspx
Marc Gravell
Thank you for your resource.
Nano HE
+2  A: 
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<mainKey, SubDict> pair1 in mainDict)
foreach (KeyValuePair<subKey, sub1Dict> pair2 in pair1.Value)
foreach (KeyValuePair<sub1Key, sub2Dict> pair3 in pair2.Value)
foreach (KeyValuePair<sub2Key, sub2Value> pair4 in pair3.Value)
{
    sb.AppendFormat("{0}/{1}/{2}/{3}, {4}", 
        pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair4.Value);
}

UPDATE:

StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, object> pair1 in mainDict)
foreach (KeyValuePair<string, object> pair2 in (Dictionary<string, object>)pair1.Value)
foreach (KeyValuePair<string, object> pair3 in (Dictionary<string, object>)pair2.Value)
foreach (KeyValuePair<string, object> pair4 in (Dictionary<string, object>)pair3.Value)
{
    sb.AppendFormat("{0}/{1}/{2}/{3}, {4}", 
        pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair4.Value);
}
Darin Dimitrov
Hi Darin, Acturally, mainDict generated from a parsing result of XSD file. There is no keyword can be inserted to my code. i declared mainDict as a static dictionary<string, object> . I am afraid i can't foreach (KeyWord Content) as your suggestion. how to extend the StringBuilder loop method to meet my requirement? thank you.
Nano HE
See if update helps.
Darin Dimitrov
sb.AppendFormat("{0}/{1}/{2}/{3}, {4}", - Can't using the fixed 4 variables. The items number will changed dynamical based on the mainDic layers. This means the mainDict generated dynamical and if the XSD file change, the mainDic must changed too. and the top code still could hande the dynamical condition.
Nano HE