Generic lists in array list

670 views Asked by At

There is a array list that contain generic lists. How can i access the variables that in generic list? But i want to access the variables via the array list.

ArrayList TheList = new ArrayList();

List<NewType>[] GenericLists = new List<NewType>[4];

GenericLists[0].Add(variable);
       .
       . 
       .
       for (int i = 0; i < 4; i++)
            {
                TheList.Add(GenericLists[i]);
            }

How can i print the variables via the Array list?

1

There are 1 answers

2
Selman Genç On

You need to iterate over the items of your ArrayList and cast each item to List<NewType> then you can iterate over the items in the lists and display them or whatever you want...

foreach(var list in TheList)
{
   var currentList = (List<NewType>)list;
   ...
}

Or you can use Linq methods to cast them:

foreach(var list in TheList.Cast<NewList>())

These assumes that all items in the array list are of type NewList. Otherwise you will get an InvalidCastException at runtime. To avoid this you can use is or as operators to check if the type is NewList, or you can use OfType method which does this for you:

foreach(var list in TheList.OfType<NewList>())