使用C#访问多级字典

时间:2014-01-29 07:05:17

标签: c# dictionary

我有一个如下的字典结构。我想编写一个代码来帮助我从字典的第二级和第三级访问对象。

Dictionary<string, Dictionary<string, Dictionary<string, string>>>

我现在有这种形式的东西。

using (StreamReader r = new StreamReader(@"C:\Users\xyz.csv"))
{
   string line;
   line = r.ReadLine();
   while (!string.IsNullOrEmpty(line))
   {
          line = r.ReadLine();
   }
   string[] sHeaders = line.Split(',');
   int iIndex = Array.IndexOf(sHeaders, "RollNo");
   while ((line = r.ReadLine()) != null)
    {
        string[] records = line.Split(',');
        string sname = records[iIndex];
        foreach (string record in records)
        {

            while(!string.IsNullOrEmpty(sname))
            {
                Dictionary<string, Dictionary<string, string>> columns = new Dictionary<string,Dictionary<string,string>>();


                 // Dont know what to do here
             }
        }

   }

xyz.csv

RollNo Name Subject1
1      abc   90
2      xyz   80
3      pqr   92
//emptyline
RollNo Name Subject2
1      abc   98
2      xyz   86
3      pqr   88
//emptyline
RollNo Name Subject3
1      abc   99
2      xyz   83
3      pqr   82

任何帮助将不胜感激..提前致谢!!

1 个答案:

答案 0 :(得分:0)

这是一个非常糟糕的设计,但这是一个示例:

var dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();

foreach (var key in dict.Keys)
{
    var currentDictionary = dict[key];
    foreach (var key2 in currentDictionary.Keys)
    {
        var nestedDictionary = currentDictionary[key2];
        foreach (var item in nestedDictionary)
        {
            var currentKey = item.Key;
            var currentValue = item.Value;
        }
    }
}