2012-12-21 34 views
1

我試圖實現的是將字符串拆分爲多個地址,如「NL,VENLO,5928PN」getLocation將返回一個「POINT(xy)」字符串值。在foreach中創建對象以推送到C#中的數組#

This Works。接下來,我需要爲每個位置創建一個WayPointDesc對象。並且每個這些對象都必須推入WayPointDesc []。我嘗試了各種方法,但到目前爲止我找不到可行的方法。我最後的手段是硬編碼最大數量的航點,但我寧願避免這樣的事情。

不幸的是,使用列表不是一種選擇...我想。

這是函數:

/* tour() 
    * Input: string route 
    * Output: string[] [0] DISTANCE [1] TIME [2] MAP 
    * Edited 21/12/12 - Davide Nguyen 
    */ 
    public string[] tour(string route) 
    { 
     // EXAMPLE INPUT FROM QUERY 
     route = "NL,HELMOND,5709EM+NL,BREDA,8249EN+NL,VENLO,5928PN"; 
     string[] waypoints = route.Split('+'); 

     // Do something completly incomprehensible 
     foreach (string point in waypoints) 
     { 
      xRoute.WaypointDesc wpdStart = new xRoute.WaypointDesc(); 
      wpdStart.wrappedCoords = new xRoute.Point[] { new xRoute.Point() }; 
      wpdStart.wrappedCoords[0].wkt = getLocation(point); 
     } 

     // Put the strange result in here somehow 
     xRoute.WaypointDesc[] waypointDesc = new xRoute.WaypointDesc[] { wpdStart }; 

     // Calculate the route information 
     xRoute.Route route = calculateRoute(waypointDesc); 
     // Generate the map, travel distance and travel time using the route information 
     string[] result = createMap(route); 
     // Return the result 
     return result; 

     //WEEKEND? 
    } 
+9

爲什麼你不能用一個列表,然後在完成時調用ToArray的就可以了? – mletterle

+1

是不是wpd超出了你目前實現的範圍? – 2012-12-21 14:26:20

+0

@mletterle謝謝。我剛剛做到了。 – Perfection

回答

5

數組是固定長度的,如果你要動態地添加元素,你需要使用某種類型的鏈表結構。另外,當你最初添加它時,你的wpdStart變量超出了範圍。

List<xRoute.WaypointDesc> waypointDesc = new List<xRoute.WaypointDesc>(); 

    // Do something completly incomprehensible 
    foreach (string point in waypoints) 
    { 
     xRoute.WaypointDesc wpdStart = new xRoute.WaypointDesc(); 
     wpdStart.wrappedCoords = new xRoute.Point[] { new xRoute.Point() }; 
     wpdStart.wrappedCoords[0].wkt = getLocation(point); 

     // Put the strange result in here somehow 
     waypointDesc.add(wpdStart); 
    } 

如果你真的想要的清單作爲一個數組後,使用:waypointDesc.ToArray()

+0

ermergurd。這是完美的。我需要補充的是。我會更頻繁地使用它。 xRoute.WaypointDesc [] finalWaypointDesc = waypointDesc.ToArray(); – Perfection

+3

FYI'列表'不是一個鏈表。它實際上是一個動態數組。 – juharr