Store n Number of Lists of Different Types in a Single Generic List

Question: Is it possible to store n number of lists of various types in a single generic list?

Answer: Yes, by creating a list of list objects.

list

So here we are creating a list that is a list of objects and in the list we can store n number of lists of various types.

Now let's understand this with an example.

Step 1: First of all we will create a console application named InterviewQuestionPart6.

console application

Step 2: Now we will create a list that is a list of objects and then we will store a different type of data, like integer and string because every type in .NET directly or indirectly inherits from System.object.

Here we will first create a list that is a list of objects, then inside this we will create one more list of objects and store integer values, then we create one more list of objects and store string values. We will now add these lists to the list of objects. Now using a force Loop we retrieve and print the items with the following code.

  1.  using System;   
  2.  using System.Collections.Generic;   
  3.  using System.Linq;   
  4.  namespace InterviewQuestionPart6   
  5.  {   
  6.     class Program   
  7.     {   
  8.        static void Main(string[] args)   
  9.        {   
  10.           //Create a List that is List of object   
  11.           List<List<object>> list=new List<List<object>>();   
  12.   
  13.           //Create a List of object   
  14.           List<object> list1=new List<object>();   
  15.           list1.Add(101);   
  16.           list1.Add(102);   
  17.           list1.Add(103);   
  18.          
  19.           //Create another List of object   
  20.           List<object> list2 = new List<object>();   
  21.           list1.Add("Hello1");   
  22.           list1.Add("Hello2");   
  23.           list1.Add("Hello3");   
  24.    
  25.           //Add the list1 and list2 to the list   
  26.           list.Add(list1);   
  27.           list.Add(list2);   
  28.    
  29.           //Print List of object that is in list   
  30.           foreach(List<object> objectlist in list)   
  31.           {   
  32.              //Print object that is in objectlist   
  33.              foreach(object obj in objectlist)   
  34.              {   
  35.                 //Print the items of object   
  36.                 Console.WriteLine(obj);   
  37.              }   
  38.              Console.WriteLine();   
  39.           }   
  40.        }   
  41.     }   
  42.  }   
Now run and see the output, so we have integers and then strings.

output

So by creating a list of a list of objects, it is possible to store n number of lists of various types in a single generic list.