如何从字典值转换为字典

时间:2013-05-28 13:50:08

标签: c# dictionary idictionary

我有一个字典,其中包含值中的另一个字典。

即:

Dictionary<string, object> primaryList = new Dictionary<string, object>();
var secondaryList = primaryList.Select(x => x.Value);

我需要将值作为secondaryList中的字典获取。我怎么能这样做?

我从以下链接获得了一个关于反序列化json的集合:

Deserialize JSON into C# dynamic object?

从对象中,我需要将主列表中的值解析为键值对。

4 个答案:

答案 0 :(得分:2)

Dictionary<T, V> - 是一个通用集合,其中T或V也可以是Dictionary。

尝试下一步:

Dictionary<string, Dictionary<object, object>> 

而不是

Dictionary<string, object>

答案 1 :(得分:1)

如果您知道它们都是字典,那么只需将字典定义为

var primaryList = new Dictionary<string, Dictionary<key-type, value-type>>();

否则,请使用OfType()过滤Values集合。

var secondaryList = primaryList.Select(x => x.Value).OfType<Dictionary<key-type, value-type>>();

如果您实际上没有使用List<>进行查找,请考虑使用Dictionary

答案 2 :(得分:0)

您可以使用Cast()扩展方法将集合中的对象强制转换为特定类型:

var secondaryList = primaryList.Select(x => x.Value)
                               .Cast<Dictionary<string, object>>();

如果集合中的任何对象无法转换为Dictionary<string, object>,则会失败并返回异常。您还可以使用OfType<Dictionary<string, object>>()仅选择那些特定类型的元素。

var secondaryList = primaryList.Select(x => x.Value)
                               .OfType<Dictionary<string, object>>();

选择字典的子集时,您可以使用ToDctionary()扩展方法。

Dictionary<string, object> l_d = new Dictionary<string, object>();
l_d.Add( "Apple", 1 );
l_d.Add( "Access", 2 );
l_d.Add( "Barber", 3 );
l_d.Add( "Bacon", 4 );

Dictionary<string, object> l_d2 = 
    l_d.Where( x => x.Key.StartsWith( "A" ) )
       .ToDictionary( kvp => kvp.Key, kvp => kvp.Value );

答案 3 :(得分:0)

 Dictionary<string, Dictionary<string, object>> value = new Dictionary<string,   Dictionary<string, object>>();

 Dictionary<string, object> childDictionary = value["SomeValue"];