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);
}
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
copyOfMapElements = JsonSerializer.Deserialize<List<MapElement>>(JsonSerializer.Serialize(list));