25

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?

Ayyash
  • 4,039
  • 7
  • 37
  • 57

7 Answers7

41
List<MyType> copy = new List<MyType>(original);
Jeffrey L Whitledge
  • 55,844
  • 9
  • 67
  • 97
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
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
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:

How do I clone a generic list in C#?

Matthew
  • 184
  • 2
  • 9