0

Can I create an exact duplicate of a list in c#?

List<string> addedAttachments = new List<string>();
addedAttachments = (List<string>)HttpContext.Current.Session["UserFeedbackImage"];

List<string> tempList = addedAttachments;

Stores tempList in a different order

Thanks

John
  • 3,965
  • 21
  • 77
  • 163

3 Answers3

3

You only assign the reference of your first list addadAttachments to a new variable, but don't create a new list.

To create a new list simply call

List<string> tempList = new List<string>(addedAttachments);

The order of the strings in the lists stays the same.


But note that this is only appropriate for immutable types like string. With a list of complex mutable objects, you would add the same objects to the new list, so if you change properties of an object in the old list, the "object in the new list" is also changed (it is the changed object). So you might also need to copy the objects.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
1

To create a copy, try Linq:

List<string> tempList = addedAttachments.ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 2
    Just for completeness: the `ToList()` extension does nothing else but `return new List(source);`, since `List` has a constructor `public List(IEnumerable source)` – René Vogt Aug 11 '16 at 15:29
1

Since you have a List<string> and string is immutable you can do:

List<string> tempList = addedAttachments.ToList();

If you have a custom object in your list then you should look for cloning.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436