Home > other >  How to add new item into a list without overwriting the old item
How to add new item into a list without overwriting the old item

Time:07-12

I'm exporting some data from database to excel using CLOSEDXML. I need to add the corresponding objects/item to each object in the 'newModelist' IQueryable and add all the object to new List. In my case new row were added in the list using list.add method, however the old record is replaced by the next row/object. I'm not quite what would be the correct way to implement this.

var getData = _db.Database.Where(y => y.identifier == Identifier);
var newModelist = new MainModel();
var listXML= new List<listXML>();

 foreach(var item in getData) 
    {
        newModelist.col1 = item.A;
        newModelist.col2 = item.B;
        newModelist.col2 = item.C;
        listXML.Add(newModelist);
    }

CodePudding user response:

You need to understand what an instance is.

You are currently modifying the same object instance. And you are adding the same instance to the List on every iteration.

Since List only stores the reference to an instance, your List currently contains multiple references to the same instance. Each index will return the same element.

If you want individual object instances you must create each using the new keyword:

foreach(var item in getData) 
{
    var newModelist = new MainModel
    {
        col1 = item.A;
        col2 = item.B;
        col3 = item.C;
    }

    listXML.Add(newModelist);
}

CodePudding user response:

newModelist (object) is a reference type and modifying the value will reflect in the all the references, so you need to create a new instance while setting the properties in the loop. Moving creation of newModelList to for loop would do

foreach(var item in getData) 
    {
        var newModelist = new MainModel();
        newModelist.col1 = item.A;
        newModelist.col2 = item.B;
        newModelist.col2 = item.C;
        listXML.Add(newModelist);
    }
  • Related