1

I am attempting to create a class 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; }


}

And then instantiate said class as a list

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

My end goal is to have a list of several different database names which each have Lists that contain said databases table names, columns, constraints etc.

However I am receiving an "Index was out of range. Must be non-negative and less than the size of the collection" error when I try to populate my lists

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

Am I instantiating something wrong? Or is this list of lists just bad code and I should pursue a different mean to my end goal?

Alexei Levenkov
  • 96,782
  • 12
  • 124
  • 169

1 Answers1

3

First, name your class with appropriate code and on the constructor, instance the collections, for sample:

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...
    }
}

And in the loop, just create a object from ComparisonData and set some values on the properties lists , for sample:

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);
}
Felipe Oriani
  • 36,796
  • 18
  • 129
  • 183
  • You'll get a NRE when adding items to those uninitialized sub-lists. – Servy Jun 09 '14 at 17:34
  • 1
    Thankyou! This solved my issue should have realized I needed to instantiate my inner lists – user3723223 Jun 09 '14 at 17:36
  • 1
    @user3723223: You are welcome. Also, since you are new to StackOverflow, I would like to inform you that you can upvote good answers and accept the answer that helped you the most by checking the tick mark next to the Answer. On this site an upvote or an accepted answer counts as a "thanks". – Olivier Jacot-Descombes Jun 09 '14 at 17:54