在foreach中创建对象以在C#中推送到数组

Per*_*ion 1 c# arrays api xserver

我想要实现的是将字符串拆分为多个地址,如"NL,VENLO,5928PN",getLocation将返回"POINT(xy)"字符串值.

这有效.接下来,我需要为每个位置创建一个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?
    }
Run Code Online (Sandbox Code Playgroud)

Wil*_* C. 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);
    }
Run Code Online (Sandbox Code Playgroud)

如果您以后真的希望列表成为数组,请使用: waypointDesc.ToArray()

  • FYI`List <T>`不是链表.它实际上是一个动态阵列. (3认同)