繁体   English   中英

C#如何填充列表列表

[英]C# how to populate list of lists

我正在尝试创建一类列表

 public class comparisonData
{
    public List<string> Tables { get; set; }
    public List<string> Constraints { get; set; }
    public List<string> StoredProcs { get; set; }
    public List<string> Views { get; set; }
    public List<string> Functions { get; set; }
    public List<string> Columns { get; set; }
    public List<string> Synonyms { get; set; }
    public List<string> NotNullables { get; set; }


}

然后将所述类实例化为列表

List<comparisonData> cList = new List<comparisonData>();

我的最终目标是拥有一个包含多个不同数据库名称的列表,每个数据库名称都包含包含所述数据库表名,列,约束等的列表。

但是,当我尝试填充列表时,我收到“索引超出范围。必须是非负数且小于集合的大小”错误

        while(reader.Read())
        {
            cList[0].Tables.Add(reader.GetString(0));
        }

我是否在实例化错误? 或者这个列表列表只是不好的代码,我应该追求与我的最终目标不同的意思?

首先,使用适当的代码为您的类命名,并在构造函数,实例集合上为样本命名:

public class ComparisonData
{
    public List<string> Tables { get; set; }
    public List<string> Constraints { get; set; }
    public List<string> StoredProcs { get; set; }
    public List<string> Views { get; set; }
    public List<string> Functions { get; set; }
    public List<string> Columns { get; set; }
    public List<string> Synonyms { get; set; }
    public List<string> NotNullables { get; set; }

    public ComparisonData()
    {
        Tables = new List<string>();
        Constraints = new List<string>();
        // other properties...
    }
}

在循环中,只需从ComparisonData创建一个对象,并在属性列表上设置一些值,用于示例:

List<ComparisonData> cList = new List<ComparisonData>();

while(reader.Read())
{
   ComparisonData c = new ComparisonData();

   c.Tables.Add(reader.GetString(0));
   // other properties

   // since it is a List, just call the Add method and pass the object
   cList.Add(c);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM