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,257
  • 9
  • 39
  • 58

7 Answers7

42
List<MyType> copy = new List<MyType>(original);
Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99
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
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
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:

How do I clone a generic list in C#?

Matthew
  • 149
  • 2
  • 11