I noticed in c# there is a method for Lists: CopyTo -> that copies to arrays, is there a nicer way to copy to a new list? problem is, I want to retrieve the list by value to be able to remove items before displaying them, i dont want the original list to be modified, that too doesnt seem to be easily attainable, any ideas?
Asked
Active
Viewed 2.4k times
7 Answers
42
List<MyType> copy = new List<MyType>(original);

Jeffrey L Whitledge
- 58,241
- 9
- 71
- 99
-
7Modifying an element in the list (not adding or removing) still impacts both lists... – Zoop Oct 12 '17 at 14:38
-
3As @Zoop said, it is not working. When inside list something is changed, it is also changed it in the original. – mbpakalin May 10 '20 at 01:33
-
It is not working – TheOligarch Dec 06 '21 at 20:29
5
I want to retrieve the list by value to be able to remove items before displaying them,
var newlist = oldList.Where(<specify condition here>).ToList();

Jimmy
- 89,068
- 17
- 119
- 137
2
If you are using .NET 3.5, the resulting array can have ToList() called on it.

John Buchanan
- 5,054
- 2
- 19
- 17
2
Just create a new List
and use the appropriate constructor:
IList<Obj> newList = new List<Obj>(oldList);

bruno conde
- 47,767
- 15
- 98
- 117
-
2Modifying an element in the list (not adding or removing) still impacts both lists... – Matheus de Lara Calache Feb 04 '20 at 12:02
2
I think this will work. Passing a list to the constructor of a new list.
List<string> list1 = new List<string>();
List<string> list2 = new List<string>(list1);

Andy West
- 12,302
- 4
- 34
- 52
-
2Modifying an element in the list (not adding or removing) still impacts both lists... – Matheus de Lara Calache Feb 04 '20 at 12:02
0
Have you tried Cloning (Clone()) each item and adding the clone to a new collection?

Chuck Conway
- 16,287
- 11
- 58
- 101
0
It seems if you have a list of references, the list
List<Object> list2 = new List<Object>(list1);
does not work.
This should solve your problem:

Matthew
- 149
- 2
- 11