Reputation:
I'm coding in C# and I have a dictionary with tons of data. One of the members is "children" but when I try to write out its values, I get: System.Object[]
I know that children contains data, probably nested data, but I'm unsure if it's a list, dictionary, array, etc.
How do I write out all the data within "children"?
Upvotes: 2
Views: 17237
Reputation: 7238
"I know that children contains data, probably nested data, but I'm unsure if it's a list, dictionary, array, etc"
So the childreen is IEnumerable or not a collection
try this code
void Iterate(object children)
{
if(children is IEnumerable data)
foreach(object item in data)
Iterate(item);
else Console.WriteLine(children.ToString());
}
Upvotes: 0
Reputation: 113
I realize that this thread is over a year old, but I wanted to post a solution I found in case anyone is wrestling with trying to get data out of the System.Object[] returned using the Cook Computing XML-RPC Library.
Once you have the Children object returned, use the following code to view the key/values contained within:
foreach (XmlRpcStruct rpcstruct in Children)
{
foreach (DictionaryEntry de in rpcstruct)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
Console.WriteLine();
}
Upvotes: 1
Reputation: 2828
(Note I didn't test this code in VS, working off memory here).
object[] children = (object[])foo["children"];
foreach(object child in children)
System.Diagnostics.Debug.WriteLine(child.GetType().FullName);
This should dump out the classnames of the children.
If you are doing a foreach on foo["children"] you shouldn't be getting a failure that a public iterator isn't found since by definition an array has one (unless I missed something).
Upvotes: 1
Reputation: 1062975
It it an array of object
references, so you will need to iterate over it and extract the objects, For example:
// could also use IEnumerable or IEnumerable<object> in
// place of object[] here
object[] arr = (object[])foo["children"];
foreach(object bar in arr) {
Console.WriteLine(bar);
}
If you know what the objects are, you can cast etc - or you can use the LINQ OfType/Cast extension methods:
foreach(string s in arr.OfType<string>()) { // just the strings
Console.WriteLine(s);
}
Or you can test each object:
foreach(object obj in arr) { // just the strings
if(obj is int) {
int i = (int) obj;
//...
}
// or with "as"
string s = obj as string;
if(s != null) {
// do something with s
}
}
Beyond that, you are going to have to add more detail...
Upvotes: 3
Reputation: 22849
The default response of any instantiated .NET type to "ToString()" is to write out the fully qualified type name.
System.Object[] means that you have an array where each element is of type "Object". This "box" could contain anything since every type in .NET derives from Object. The following may tell you what the array really contains in terms of instantiated types:
foreach (object o in children)
Console.WriteLine(o != null ? o.GetType().FullName : "null");
Upvotes: 3