2

I have a List,with 11k items, the list is filled on initialization and I need to pass a copy for a function that will modify the passed list items without modifying the original copy,

The only way i found till now is to copy the list item by item to another list with creating new custom_class() each time which consumes ~50ms which is not acceptable in my case.

What I tried so far is:

AnotherOriginal = Original.AsReadOnly().tolist();  
copy = original.tolist();  

modifying copy[0].testvariable will modify both : AnotherOriginal and original. and

I also tried

ImmutableList test = original.ToImmutableList()

modifying test[0].testvariable will be also reflected to the original!

What is fastest way to get a copy to be passed to the function without having to add items one by one to another list? with preventing modification on the original list.

current deep copy code(which i need to enhance):

List<FP_Point> particles = new List<FP_Point>();
foreach (FP_Point p in originalParticles)
{
    particles.Add(new FP_Point() { ID = p.ID, ZonesIDs = p.ZonesIDs, Location = new Point(p.Location.X, p.Location.Y), Readings = p.GetReadings() });
}
return particles;

Custom class:

public class FP_Point
{
    public int ID { get; set; }
    public Point Location { get; set; }
    public List<Reading> Readings { get; set; }
    public double Weight, Distance;
    public List<int> ZonesIDs;
    public double PreviousDistance;
}
AbuS3ood
  • 21
  • 2
  • 3
    There is 2 type of copy: shallow copy and deep copy. You must use deep copy to prevent reference between your array list. Try this: http://stackoverflow.com/questions/18066429/shallow-copy-or-deep-copy – Imran Sh Sep 08 '16 at 11:19
  • 1
    Possible duplicate of [How create a new deep copy (clone) of a List?](http://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt) – DNKROZ Sep 08 '16 at 11:22
  • 1
    `ToList()` will create a new List, but both lists contain references to the same objects. Your foreach loop makes copies of those objects, so that's why it works. – Dennis_E Sep 08 '16 at 11:25

1 Answers1

0

In addition to cloning choice and assuming that GetReadings() function returns a fresh instance of List<Readings>, following may be used:

var particles = originalParticles.Select(p => new FP_Point()
{
    ID = p.ID,
    ZonesIDs = p.ZonesIDs != null ? p.ZonesIDs.ToList() : null,
    Location = new Point(p.Location.X, p.Location.Y),
    Readings = p.GetReadings(),
    Distance = p.Distance,
    PreviousDistance = p.PreviousDistance, 
    Weight = p.Weight
}).ToList();
Halis S.
  • 446
  • 2
  • 11