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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
List<MyType> copy = new List<MyType>(original);
Method 2
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();
Method 3
If you are using .NET 3.5, the resulting array can have ToList() called on it.
Method 4
Just create a new List and use the appropriate constructor:
IList<Obj> newList = new List<Obj>(oldList);
Method 5
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);
Method 6
Have you tried Cloning (Clone()) each item and adding the clone to a new collection?
Method 7
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:
How do I clone a generic list in C#?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0