Search code examples
c#listinstantiationpoints

Multiple problems with a 2D List of Points


I am having multiple problems with a 2D List of Points. The Points are the To and From Points of a series of lines.

First, this code snippet is from the declaration of the List. It is part of larger class called TacLineStruct:

// The actual MST Spine
public List <Point> [,] MSTSpine 
{
    get;
    set;
}

public TacLineStruct(int arrayLength)
{
    GroupID = new int[arrayLength];
    this.EdgeList = new int[(arrayLength * arrayLength), 2];
    EdgeWeight = new float[arrayLength * arrayLength];
    GroupCenter = new Point[arrayLength];
    this.MSTSpine = new List<Point>[arrayLength,2];
}

Next, these assignments cause a runtime error:

Point tPoint1 = new Point((int)Army[TLS.EdgeList[i, 0]].Location.X, (int)Army[TLS.EdgeList[i, 0]].Location.Y);
Point tPoint2 = new Point((int)Army[TLS.EdgeList[i, 1]].Location.X, (int)Army[TLS.EdgeList[i, 1]].Location.Y);

TLS.MSTSpine[i,0].Add(tPoint1);
TLS.MSTSpine[i,1].Add(tPoint2);

Lastly, how do you find the Count for the List? This doesn't work:

for(int i = 0; i < TLS.MSTSpine[0,0].Count(); i++) 

I posted a question earlier asking for the correct way to declare, instantiate, and reference a List of matched Points but was immediately downvoted. I've looked all over and have yet to find this problem covered either on StackOverflow or in any of my manuals.


Solution

  • It would make things easier if you declared a Line struct:

    public struct Line
    {
        public Line(Point start, Point end)
        {
            Start = start;
            End = end;
        }
    
        public Point Start { get; }
        public Point End { get; }
    
        public override string ToString()
        {
            return String.Format($"({Start.X}, {Start.Y}) - ({End.X}, {End.Y})");
        }
    }
    

    Now the list of lines can be declared as

    public List<Line> MSTSpine { get; } = new List<Line>();
    

    and be used like this

    var p1 = new Point(1, 2);
    var p2 = new Point(3, 4);
    var line = new Line(p1, p2);
    MSTSpine.Add(line);
    
    Console.WriteLine(MSTSpine[0].Start.X);
    
    Console.WriteLine(MSTSpine[0]); // Prints:  (1, 2) - (3, 4)
    

    I saw that you also declared a EdgeWeight array. Instead I would add the weight a property to the Line struct.