0

I want to get the values and keys of the Object. First I cast it and then put it on the foreach loop to get keys and values.

object itemAttributes = web.javaScriptExecutor().ExecuteScript($"return window.INITIAL_STATE.items.itemAttributes")

                    var items = (ReadOnlyCollection<object>)itemAttributes;


                        foreach (Dictionary<string, object> item in items)
                        {
                            foreach (KeyValuePair<string, object> kvp in item)
                            {
                                if (Convert.ToString(kvp.Value) != null)
                                {
                                     Name = Convert.ToString(kvp.Key), Value = Convert.ToString(kvp.Value) });
                                }
                            }
                        }

I get an error when I want to cast

var items = (ReadOnlyCollection<object>)itemAttributes;

//Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]'.
D.JCode
  • 386
  • 2
  • 12
  • Why `ReadOnlyCollection`? Why ``? In the next line you are enumerating `items` as if you have `IEnumerable>`, but `itemsAttributes` seems to be just a single dictionary. Remove that first `foreach` and assign `var item = (Dictionary)itemAttributes`. – Sinatr Nov 12 '20 at 13:58
  • @Sinatr I made a big mistake. thanks so much. the problem was solved – D.JCode Nov 12 '20 at 14:10

0 Answers0