erik_bradshaw
asked on
Iterating through an object which contains a list
I have an object of type object which I know contains a list (both because of the nature of the problem and because I can see it in the debugger). I want to be able to iterate through the members of the list.
My problen is that I can't work how to cast the object onto an interface that would allow iteration. I have tried:
List<object> objList = (List<object>)objectContai ningList;
System.Array variantArray = (Array)objectContainingLis t;
My problen is that I can't work how to cast the object onto an interface that would allow iteration. I have tried:
List<object> objList = (List<object>)objectContai
System.Array variantArray = (Array)objectContainingLis
//Simplified example of the problem:
//Generate a list containing integers
List<int> intList = new
intList.Add(1);
intList.Add(5);
intList.Add(7);
//Loose all info about the object, remember this is a hypothetical example!
object objectContainingList = intList;
//Now I want to loop through the object
foreach (object obj in objectContainingList)
{
Console.WriteLine(obj.ToString();
}
ASKER
The problem is a bit more complex than my simple example. I don't know either the type of object contained in the parent object nor the type of enumerable object, hence objectContainingList could be things like:
System.Array
System.Data.Linq.Table
Any member of System.Collections
All I know for certain is that the parent object (List<int> in the example above) supports the IEnumerable interface
System.Array
System.Data.Linq.Table
Any member of System.Collections
All I know for certain is that the parent object (List<int> in the example above) supports the IEnumerable interface
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
The above will print 10 and 12 to the debug output window. Note that the following would NOT work:
IEnumerable<object> castedEnum= (IEnumerable<object>) oUnknownEnumerableType;
because there's no explicit conversion to cast everything inside the list to another type, even though you request the "cath-all" type of object.ASKER
Worked great, thanks for all your help. It's so easy, can't believe I spent so much time battling with reflection to try and sort it out!
Open in new window