I have two lists, the original one and a copied one. I made a copy of the original list, because of one reason:
I need to process/work data from the original list, but I shouldn't edit it. So I created a copy of that original list to work with. But somehow changes I do on the copied list still modifies the original.
Here is my code:
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();
}
After I saw the replies, I read @sachin's post and wrote a code similar to theirs. Is this alright? It looks like it's working right now, but I am not sure is this solution ok?
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;
}
}