我有兩份名單,原來並複製一個,我做原單的複印件,因爲一個原因:「複製」列表所做的更改反映原始列表 - C#
我需要處理/工作數據從原始列表,但我不應該編輯原始列表!所以我創建了該原始列表的副本。但不知怎的,我在我的原始列表中反映了我在複製列表中做的更改。
這裏是我的代碼:
forPrintKitchenOrders = new List<OrderTemp>();
foreach (var itemss in forPrintKitchen)
{
forPrintKitchenOrders.Add(itemss); // HERE I AM ADDING ITEMS TO ANOTHER LIST BECAUSE I DON'T WANT TO EDIT ORIGINAL LIST (Change quantity etc)
}
if (forPrintKitchen.Count > 0)
{
foreach (var item in forPrintKitchenOrders.ToList())
{
foreach (var item2 in mainList)
{
if (item2.MainProductID == Convert.ToInt32(item._articleCode))
{
//I don't know why this is happening. I loop another list (copy of original list, because I didn't want to harm original list), and when I find certain item I am reducing quantity (-1),
//And later I realized and saw while I was debugging, that the value of quantity in my original "forPrintKitchen" list is also edited, I don't know how changed reflected there..
int calculate = Convert.ToInt32(item._quantity)-1; //this block is making me trouble, here I am reducing quantity and later that reflects to my forPrintKitchen list even if I am editing and looping //forPrintKitchenOrders(original's copy)
item._quantity = calculate.ToString();
}
}
}
foreach (var items in forPrintKitchen) //THIS IS MY ORIGILAN LIST AND SHE SHOULD NOT BE EDITED WHEN I EDIT "forPrintKitchenOrders" item
{
//Original List
OrdersKitchen kitchen = new OrdersKitchen();
kitchen.ProductID = Convert.ToInt32(items._articleCode);
kitchen.UserID = Util.User.UserID;
kitchen.UserName = Util.User.FirstName
kitchen.LastName = Util.User.LastName
kitchen.BillID = bill.BillID;
kitchen.Quantity = Convert.ToInt32(items._Quantity);
OrdersKitchen.Add(kitchen);
}
foreach (var itemss in mainList)
{
OrdersKitchen kitchen2 = new OrdersKitchen();
kitchen2.ProductID = Convert.ToInt32(itemss.MainProductID);
kitchen2.UserID = User.UserID;
kitchen2.UserName = Util.User.FirstName;
kitchen2.LastName = Util.User.LastName;
kitchen2.BillID = bill.BillID;
kitchen2.Quantity = Convert.ToInt32(0); //HARDCODE ZERO
OrdersKitchen.Add(kitchen2);
}
}
mainList.Clear();
//forPrintKitchenOrders.Clear();
}
編輯: 此後,我看見您的答覆GUYS我跟着@薩欽的帖子,寫類似的代碼,所以這是還好吧?順便說一句,它現在看起來像它的工作......但我不確定這個解決方案好嗎?
foreach (var itemss in forPrintKitchenOrders)
{
forPrintKitchenOrders.Add(new OrderTemp(itemss._articleCode,itemss._name,itemss._quantity,itemss._amount));
}
public class OrderTemp
{
public string _articleCode;
public string _name;
public string _quantity;
public double _amount;
public OrderTemp(string articleCode, string name, string quantity, double amount)
{
_articleCode = amount;
_name = name;
_quantity = quantity;
_amount = amount;
}
}
這些是引用相同對象的兩個列表。你創建一個新的**集**,它引用舊**集**的相同對象。如果你改變了第一個對象的屬性,那麼它在第二個被改變。這是因爲你使用的對象是引用類型而不是值類型。 – user3185569
請參閱:http://stackoverflow.com/q/14007405/1136211 – Clemens
由於@ user3185569對第一篇文章發表評論,您不會將對象從一個列表應用到另一個列表。您正在處理參考。喲必須改變'forPrintKitchenOrders.Add(itemss);'to'forPrintKitchenOrders.Add(itemss。克隆());' – Rumpelstinsk