繁体   English   中英

使用C#中的字典提取字典中的键和值

[英]Extracting key and values in dictionary with in dictionary in C#

我有一个看起来像这样的数据集合:

Dictionary<string, Dictionary<string,IEnumerable<AGString>>> Data = new Dictionary<string, Dictionary<string,IEnumerable<AGString>>>();

Dictionary<string,IEnumerable<AGString>> stdData = new Dictionary<string,IEnumerable<AGString>>();

稍后,我必须提取这些数据并将它们放置在另一个数据结构中,例如,我按如下所示构成了Data:

stdData.Add(item.ObjectName,item.Contents); // this creates the inner dictionary
Data.Add(collection,stdData); //This creates the final Data dictionary

我试图使用Data.Key,Data.Keys提取信息,但是我无法提取数据。 有什么线索吗?

绝对不知道您要做什么

给定

Dictionary<string, Dictionary<string,IEnumerable<AGString>>> Data = new Dictionary<string, Dictionary<string,IEnumerable<AGString>>>();

foreach(string k1 in Data.Keys)
{
   foreach(string k2 in Data[k1].Keys)
   {
      foreach(AGString ag in Data[k1][k2])
      {
         // do something with k1, k2 and ag
      }
   }
} 

因此,解决此问题的绝佳方法是使用Linq,而您无需购买元音。 该结构包含内部字典和外部字典。 我们可以通过Linq访问它们,如下所示:

 var flatKeyValue = from outer in Data
                               from inner in outer.Value
                               select new
                               {
                                   NewKey = outer.Key,
                                   NewVal1 = inner.Key,
                                   NewVal2 = inner.Value
                               };

因此,现在我们可以通过一个简单的foreach循环访问心爱的数据:

foreach (var item in flatKeyValue)
{
   Console.WriteLine(item.NewKey);  // you can try NewVal1, NewVal2 quite simply here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM