Home > Net >  How to copy List<MapElement> by value and not by reference?
How to copy List<MapElement> by value and not by reference?

Time:08-13

I'm attempting to copy a List<Windows.UI.Xaml.Controls.Maps.MapElement> but have so far only managed to copy the reference. Can anyone offer a way to do this without creating the original MapIcon object again.

I now understand why the methods i've attempted don't work, but i can't find a way around it.

public void MyTestFunction(BasicGeoposition nPosition) 
{

List<MapElement> MyLandmarks = new List<MapElement>();

Geopoint nPoint = new Geopoint(nPosition, AltitudeReferenceSystem.Ellipsoid);

var needleIcon = new MapIcon    //has base class MapElement
{
    Location = nPoint,                      
    NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 0.5),                    
    ZIndex = 0,                    
    Title = "Point 1"
};
            
MyLandmarks.Add(needleIcon);

// Copy Mylandmarks by value 
// Attempt 1 - copies reference
// copyOfMapElements = new List<MapElement>();
// copyOfMapElements = MyLandmarks;
//
// Attempt 2 - copies reference

copyOfMapElements = new List<MapElement>(MyLandmarks);
}

CodePudding user response:

Simple answer with only MapIcon items in the list:

copyOfMapElements = MyLandmarks.ConvertAll(lm => new MapIcon {
    Location = lm.Location,
    NormalizedAnchorPoint = lm.NormalizedAnchorPoint,
    ZIndex = lm.ZIndex,
    Title = lm.Title
});

But since MapIcon is derived from MapElement class and MyLandmarks list holds MapElement and not MapIcon which has its own set of properties you cannot use the example above (kinda weird there's no ICloneable interface implemented for these classes), so I'd probably check for the type of the element and create new instance accordingly.

CodePudding user response:

You can use LINQ to do that:

copyOfMapElements = MyLandmarks.Select(l => new MapIcon{ Location = l.Location,                      
    NormalizedAnchorPoint = l.NormalizedAnchorPoint,                    
    ZIndex = l.ZIndex,                    
    Title = l.Title }).ToList();

Update: The above solution assumes that all list elements of type MapIcon only, but if you need more generic solution to handle all MapElement derived types then you can used serialization or reflection. Check this answer for JSON serialization: https://stackoverflow.com/a/55831822/4518630

  • Related