Question

I have a dictionary which holds another dictionary within the value.

i.e.:

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

I need to get the value as a dictionary in secondaryList. How can i do that?

I'm getting a collection on deserializing the json from the following link:

Deserialize JSON into C# dynamic object?

From the object, i need to parse the value from the primary list to a key value pair.

Was it helpful?

Solution 3

You can use the Cast() extension method to cast objects in a collection to a specific type:

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

This will fail with an exception if any of the objects in the collection are not cast-able to Dictionary<string, object>. You can also use OfType<Dictionary<string, object>>() to select only those elements which are of that particular type.

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

When selecting a subset of a dictionary, you can use the ToDctionary() extension method.

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 );

OTHER TIPS

Dictionary<T, V>- is a generic collection, where T or V can be Dictionary too.

Try next:

Dictionary<string, Dictionary<object, object>> 

instead of

Dictionary<string, object>

If you know they are all dictionaries then just define your dictionary as

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

Otherwise use OfType() to filter the Values collection.

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

Consider using a List<> if you're not actually using Dictionary to do lookups.

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

 Dictionary<string, object> childDictionary = value["SomeValue"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top