The reason that deleting from list2 is also removed from list1 is because both list1 and list2 are reference types. I mean, list1 and list2 basically store where your list is somewhere in memory. When you set list2 to list1 with the = operator, what you are actually doing is to say list2 "it's good that you are going to point to the same place in memory that list1 points to." This means that if you change something using reference list1, it will look like this change is duplicated for list2 (but in fact it just changes the same data). To get around this, instead
list2 = list1;
I think you could use this (as Yuri Faktorovich said):
Edit: try
class Program { private static IList<string> list1 = new List<string>() { "v1001", "v1002", "v1003", "v1004" }; private static IList<string> list2 = new List<string>(list1); static void Main(string[] args) { list1.Remove("v1001"); print(list1); print(list2); } private static void print(IList<string> list) { foreach (string str in list) { Console.WriteLine(str); } Console.WriteLine(); } }
source share