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.
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.
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace InterviewQuestionPart6
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- List<List<object>> list=new List<List<object>>();
-
-
- List<object> list1=new List<object>();
- list1.Add(101);
- list1.Add(102);
- list1.Add(103);
-
-
- List<object> list2 = new List<object>();
- list1.Add("Hello1");
- list1.Add("Hello2");
- list1.Add("Hello3");
-
-
- list.Add(list1);
- list.Add(list2);
-
-
- foreach(List<object> objectlist in list)
- {
-
- foreach(object obj in objectlist)
- {
-
- Console.WriteLine(obj);
- }
- Console.WriteLine();
- }
- }
- }
- }
Now run and see the output, so we have integers and then strings.
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.