C#如何填充列表列表

时间:2014-06-09 17:17:09

标签: c# indexoutofboundsexception

我正在尝试创建一类列表

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

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

1 个答案:

答案 0 :(得分:3)

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

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