How to transfer items from one static list to another

I have two static lists, namely list1 and list2

private static IList<String> list1; private static IList<String> list2; list1 = new List<String>() { "v1001", "v1002", "v1003","v1004" }; 

I am trying to pass list1 elements to list2

list2 = list1 ;

Now, when I try to remove something from list2, this item is also removed from list1.

 var version = "v1001" list2.Remove(version); 

How can I do this, that I can only remove from list2 without the obstruction of list1.

+4
source share
3 answers

Both list 2 and list 1 in your exmaple are the same object with the variables list2 and list1 pointing to it. you can use

 list2 = new List<string>(list1); 

which will make them different objects.

+4
source

You can use the copy constructor:

 list2 = new List<string>(list1); 

or use Linq:

 list2 = list1.Select(s => s).ToList(); 

which could also be called statically:

 list2 = Enumerable<string>.ToList(list1); 

NOTE. Other examples are for reference only - the copy constructor specified in Yuri's answer is the cleanest way.

+4
source

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(); } } 
+2
source

Source: https://habr.com/ru/post/1499991/


All Articles