[英]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.