繁体   English   中英

将项目添加到列表对象C#中的属性(列表对象类型)

[英]add item to property(list object type) in list object c#

class temp
{
    public List<table> tables { get; set; }
    public string name { get; set; }
}

class table
{
    public string table { get; set; }
    public string table_type { get; set; }
}

List<temp> lst_temp = new List<temp>();
temp temp = new temp();
temp.name = "CUS";
lst_temp.Add(temp) 

我想在temp.tables中添加新表,但出现此错误:

附加信息:对象引用未设置为对象的实例。

这些是我尝试过但仍然失败的方法,因此我必须做的是:

table table = new table();
temp tem = lst_temp.SingleOrDefault(x => x.name == "CUS");
tem.tables.Add(syn_table);

要么

table table = new table();
lst_temp_syn.Where(x => x.name == "CUS")
  .Select(x => { x.tables.Add(table); return x; })
  .ToList();

要么

table table = new table();
foreach (temp tem in lst_temp)
  {
      if(tem.name = "CUS")
        tem.tables.Add(table); 
  }

您需要在temp的构造函数或初始化程序中构建表集合:

class temp
{
    public List<table> tables { get; set; }
    public string name { get; set; }

    public temp()
    {
        tables = new List<table>();
    }
}

暂无
暂无

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

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