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.2k times
7 Answers
41
List<MyType> copy = new List<MyType>(original);
Jeffrey L Whitledge
- 55,844
- 9
- 67
- 97
-
6Modifying 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
- 85,597
- 17
- 118
- 137
2
If you are using .NET 3.5, the resulting array can have ToList() called on it.
John Buchanan
- 4,776
- 2
- 17
- 17
2
Just create a new List and use the appropriate constructor:
IList<Obj> newList = new List<Obj>(oldList);
bruno conde
- 47,131
- 14
- 97
- 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,004
- 3
- 33
- 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,041
- 10
- 58
- 100
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
- 184
- 2
- 9