开发者

Unable to read values from Nested SortedDictionary in C#

HI

I am using nested SortedDictionary in my code as SortedDictionary<string, SortedDictiona开发者_StackOverflow社区ry<string, int>> but not able to use value stored in this object. Please find the code which i am using

SortedDictionary<string, SortedDictionary<string, int>> baseItemCounts = 
     new SortedDictionary<string, SortedDictionary<string, int>>();
            baseItemCounts.Add("1450", new SortedDictionary<string, int>());
            baseItemCounts["1450"].Add("1450M", 15);

I want to print these values on screen. but don't know how to access it.

1450

1450M ==== 15


Please some one can help?


SwDevMan81 is correct: baseItemCounts["1450"]["1450M"] will return 15.

If you want to go through the list and return sorted values, try this:

        foreach (string key1 in baseItemCounts.Keys)
        {
            foreach (string key2 in baseItemCounts[key1].Keys)
            {
                Console.WriteLine("{0}, {1}, {2}", key1, key2, baseItemCounts[key1][key2]);
            }
        }

Remember to iterate by keys so that you get the benefit of the sorting.


baseItemCounts["1450"]["1450M"] should give you 15 since the first index will give you the Value back (which is the second SortedDictionary), so then you just use the second index to get the Value out of the second SortedDictionary, which is your value.

To print the count values out:

     SortedDictionary<string, SortedDictionary<string, int>> baseItemCounts = new SortedDictionary<string, SortedDictionary<string, int>>();
     baseItemCounts.Add("1450", new SortedDictionary<string, int>());
     baseItemCounts["1450"].Add("1450M", 10);
     baseItemCounts["1450"].Add("1350M", 20);
     baseItemCounts["1450"].Add("1250M", 30);
     foreach (SortedDictionary<string, int> sd in baseItemCounts.Values)
     {
           foreach (int count in sd.Values)
           {
              Console.WriteLine("{0}", count);
           }
     }


   SortedDictionary<string, SortedDictionary<string, int>> baseItemCounts =
  new SortedDictionary<string, SortedDictionary<string, int>>();
        baseItemCounts.Add("1450", new SortedDictionary<string, int>());
        baseItemCounts["1450"].Add("1450M", 15);
        foreach (KeyValuePair<string, SortedDictionary<string, int>> kv in baseItemCounts)
        {
            Console.WriteLine(kv.Key);
            foreach (KeyValuePair<string, int> x in kv.Value)
                Console.WriteLine(x.Key + "==>" + x.Value);
        }

that will do it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜