Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign List<T> to another List<T> by value not reference [duplicate]

Tags:

c#

list

Ok so I have List list1 that I pulled from db and I want to temporary save this to List list2, perform some operation on my list1 save it to db and then play with list2 and save it to db. The problem is that because is is passed by reference once I change some fields in list1, list2 is already updated.

Is there any way to pass whole list as a value not reference?

Here is some code to make it clearer :

var CurrentMenuItems = dbContext.menu_items.Where(m => m.optgroup == currentGroup && m.day_id == menuItem.day_id).ToList();

           List<menu_item> MenuItemsToBeEditedAfterSubmitChanges = CurrentMenuItems;// we need to store this by value, so we can update it later


            byte ItemIncrease = 50; // To store temp value so we can avoid duplicate entry for item number 

            foreach (var item in CurrentMenuItems)
            {
                item.optgroup = nextGroup;
                item.item = ItemIncrease;

                ItemIncrease++; 
            }

            var menuItemsToBeReplaced = dbContext.menu_items.Where(m => m.optgroup == nextGroup && m.day_id == menuItem.day_id).ToList(); // we want to move all items within this group

            dbContext.SubmitChanges();

            foreach (var item in menuItemsToBeReplaced)
            {
                item.optgroup = currentGroup;

                item.item = (byte)(item.item - 1);

            }

            dbContext.SubmitChanges();

            // After first save, update the first group of menu items

            foreach (var item in MenuItemsToBeEditedAfterSubmitChanges)
            {

                item.optgroup = nextGroup;
                item.item = (byte)(item.item + 1);

            }

            dbContext.SubmitChanges();
like image 428
Adam Bielecki Avatar asked Dec 31 '25 13:12

Adam Bielecki


1 Answers

You could try using the List<T> constructor that takes an IEnumerable<T>. Example:

List<int> originalList = new List<int>() { 0, 1, 2 };
List<int> copiedList = new List<int>(originalList);
copiedList[2] = 3; // originalList[2] still is 2
like image 188
feralin Avatar answered Jan 02 '26 01:01

feralin