Home > Enterprise >  Update object before add to the list
Update object before add to the list

Time:10-01

I have some problem with update objects before I add them to list. For example when I have one object in lst and i get another one from _context with the same id and update param, object already added to the list also is updated. It looks like they have same address, but how?

Could anybody solve my problem?

List<Item> lst = new List<Item>();         
                foreach (Item currItemB in itemsB)
                {

                    Item newItem = new Item();
                    newItem = await _context.Item.Where(x => x.id == currItemB.id).FirstOrDefaultAsync();
                    newItem.param = currItemB.param;
      
                    lst.Add(newItem);

                }

CodePudding user response:

You are not actually creating a copy of the object. You are just using another pointer to the same address. In order to make the code run, you should create a copy from the "Item". Create a clone function in the class "Item". see 5 Ways to Clone An Object in C#

  •  Tags:  
  • c#
  • Related