- Home /
Iterate a List of different types
I have an IList containing different types of variables. How do I iterate through it? in the code below: foreach (int obj in listOfObjects) requires the variable type or it throws an error.
IList<object> listOfObjects = new List<object> { };
listOfObjects.Add("test");
listOfObjects.Add(12);
listOfObjects.Add(4.53342);
foreach (int obj in listOfObjects)
{
Debug.Log (obj.weight);
}
</object></object>
Edit:
Change this:
foreach (int obj in listOfObjects)
{
Debug.Log (obj.weight);
}
to this:
foreach (object obj in listOfObjects)
{
Debug.Log (obj.weight);
}
and this:
new List<object> { };
to this:
new List<object>();
Please format your code. It appears you used {} ins$$anonymous$$d of
Edit: now you have {} ins$$anonymous$$d of () at the end of the list def line
http://stackoverflow.com/questions/1367539/ilistint-vs-listint
Are you intending to use IList or just getting that because your .cs header needs using System.Collections.Generic;
Answer by Eric5h5 · Feb 08, 2014 at 06:32 AM
It throws an error because you're attempting to cast the "obj" variable to an int, even though most of the items in the List aren't ints. The "obj" variable should be of type object since the List is of type object.