如何将具有不同数据类型列表的列表作为子列表

本文关键字:列表 数据类型 | 更新日期: 2023-09-27 18:28:23

我想要一个方法返回一个列表,该列表包含另外两个具有两种不同数据类型的列表,如:

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;

根据上面的代码,我得到了一个错误

与"System.Collections.Generic.List>.Add(System.Collections.Generic.List)"匹配的最佳重载方法具有一些无效参数

请有人给我建议处理这个问题的最佳方法。

感谢

如何将具有不同数据类型列表的列表作为子列表

像这样创建类的对象怎么样?

 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);
   }

我不知道为什么要混合这样的对象,但可以使用ArrayList。参考以下示例:

 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

更新

在你的情况下,使用下面这样的数组列表可能会更好

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