nik_boyz
nik_boyz

Reputation: 165

How to have a list with different data types of lists in it as a sublists?

I want a method to return a list which contains two more list which are having two different data types, like :

List<List<object>> parentList = new List<List<object>>();
List<string> childList1 = new List<string>();
List<DataRow> childList2 = new List<DataRow>();
parentList.Add(childList1);
parentList.Add(childList2);
return parentList;

As per above code I am getting an error

The best overloaded method match for 'System.Collections.Generic.List>.Add(System.Collections.Generic.List)' has some invalid arguments

Please can anyone suggest me the best approach to handle this.

Thanks

Upvotes: 5

Views: 116

Answers (2)

Ankit Vijay
Ankit Vijay

Reputation: 4108

I'm not sure why would you like to mix objects like this, but you could use ArrayList for this. Refer example below:

 List<ArrayList> data = new List<ArrayList>();
 data.Add(new ArrayList(){12, "12"});   //Added number and string in ArrayList
 data.Add(new ArrayList() {"12", new object() }); //Added string and object in ArrayList

Update

In your case the using the array list like below could be better

var data = new ArrayList();
data.Add(new List<object>());
data.Add(new List<string>());
data.Add(new List<int>());

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29036

What about creating an object of your class as like this?

 public class myParent
    {
        public List<string> childList1 = new List<string>();
        public List<DataRow> childList2 = new List<DataRow>();
    }
 public void someFun()
  {
        List<myParent> parentList = new List<myParent>();
        myParent myParentObject = new myParent();
        myParentObject.childList1 = new List<string>() { "sample" };
        myParentObject.childList2 = new List<DataRow>() { };
        parentList.Add(myParentObject);
   }

Upvotes: 3

Related Questions