Link to home
Start Free TrialLog in
Avatar of erik_bradshaw
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>)objectContainingList;
System.Array variantArray = (Array)objectContainingList;



//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();
}

Open in new window

Avatar of abel
abel
Flag of Netherlands image

You need to do the following for this to work (you changed the List object to a type of object, not the items in that list):

List<int> castedList = (List<int>) objectContainingList;
foreach (int myInt in castedList )
{
   Console.WriteLine(myInt .ToString();
}

Open in new window

Avatar of erik_bradshaw
erik_bradshaw

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
ASKER CERTIFIED SOLUTION
Avatar of abel
abel
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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!