C# 通过值而不是引用将 List<T> 分配给另一个 List<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15618678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign List<T> to another List<T> by value not reference
提问by Adam Bielecki
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.
好的,所以我有从 db 中提取的 List list1,我想将它临时保存到 List list2,对我的 list1 执行一些操作将其保存到 db,然后使用 list2 并将其保存到 db。问题是,因为一旦我更改了 list1 中的某些字段,就会通过引用传递,所以 list2 已经更新。
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();
回答by feralin
You could try using the List<T>
constructor that takes an IEnumerable<T>
. Example:
您可以尝试使用List<T>
带有IEnumerable<T>
. 例子:
List<int> originalList = new List<int>() { 0, 1, 2 };
List<int> copiedList = new List<int>(originalList);
copiedList[2] = 3; // originalList[2] still is 2
回答by Caleb Keith
List<object> list2 = new List<object>(list1);
This should prevent you from referencing the other list because the values are copied.
这应该可以防止您引用其他列表,因为值已被复制。
回答by Fabio Marcolini
I think that the given answer work only for value type. For reference type you should implement a clone method that copy all the data on a new instance of the same class Then for each element in the list you add in another list the cloned object
我认为给定的答案仅适用于值类型。对于引用类型,您应该实现一个克隆方法,该方法将所有数据复制到同一类的新实例上然后对于列表中的每个元素,您将克隆对象添加到另一个列表中
回答by Daniil
Just Another Yet Solution:
另一个解决方案:
IList<string> f = new List<string>();
var t = f.ToList();