JimmyN
JimmyN

Reputation: 599

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) 

I want add new table in temp.tables but got this error:

Additional information: Object reference not set to an instance of an object.

These are the ways I tried,but still failed, so what I have to do:

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

or

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

or

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

Upvotes: 0

Views: 250

Answers (1)

vc 74
vc 74

Reputation: 38179

You need to build the tables collection in the constructor of temp or in an initializer:

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

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

Upvotes: 4

Related Questions