The following line is most likely the culprit:
enumerateValues(iEnumerator.Current.Value, childNode);
Because the enumerateValues
method accepts a IEnumerator<KeyValuePair<string, object>>
, the values of the key-value pairs will always be of type object
. Therefore you cannot call the method with iEnumerator.Current.Value
, because the value isn't of type IEnumerator<KeyValuePair<string, object>>
.
This is exactly what the error message tells you:
Argument '1': cannot convert from 'object' to 'System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string,object>>'
You will have to cast iEnumerator.Current.Value
to the correct type first, before you can call the method. You can do this using the as operator.
private void enumerateValues(IEnumerator<KeyValuePair<string, object>> iEnumerator, TreeNode parentnode)
{
// Loop through the values.
while (iEnumerator.MoveNext())
{
// Try a 'safe' cast of the current value.
// If the cast fails, childEnumerator will be null.
var childEnumerator = iEnumerator.Current.Value as IEnumerator<KeyValuePair<string, object>>;
if (childEnumerator != null)
{
TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Key);
enumerateValues(childEnumerator, childNode);
}
else
{
TreeNode childNode = parentnode.Nodes.Add(iEnumerator.Current.Value.ToString());
}
}
}
I also suggest you use IEnumerable<T>
instead of IEnumerator<T>
, if you can. It shows the intent of the code more clearly, you won't have to handle the iteration manually and you can use LINQ on it.
private void enumerateValues(IEnumerable<KeyValuePair<string, object>> items, TreeNode parentnode)
{
foreach (var item in items)
{
// Try a 'safe' cast of the current value.
// If the cast fails, childEnumerator will be null.
var childEnumerator = item.Value as IEnumerable<KeyValuePair<string, object>>;
if (childEnumerator != null)
{
TreeNode childNode = parentnode.Nodes.Add(item.Key);
enumerateValues(childEnumerator, childNode);
}
else
{
TreeNode childNode = parentnode.Nodes.Add(item.Value.ToString());
}
}
}