Search code examples
c#locationelementrevit

Revit Element.Location to XYZ


I'm trying to create a List<XYZ> or XYZ[ ] from a List<Element>.  Both Location and XYZ are members of the Autodesk.Revit.DB namespace, but there doesn't seem to be a conversion method.  Does anyone know of one, or have you created something that may be able to help me out?


Solution

  • Sure. Here goes:

          List<Element> walls = new List<Element>();
    
          XYZ p;
          List<XYZ> wall_start_points
            = walls.Select<Element, XYZ>( e => {
              Util.GetElementLocation( out p, e );
                return p; } )
                  .ToList<XYZ>();
    
    
    /// <summary>
            ///     Return a location for the given element using
            ///     its LocationPoint Point property,
            ///     LocationCurve start point, whichever
            ///     is available.
            /// </summary>
            /// <param name="p">Return element location point</param>
            /// <param name="e">Revit Element</param>
            /// <returns>
            ///     True if a location point is available
            ///     for the given element, otherwise false.
            /// </returns>
            public static bool GetElementLocation(
                out XYZ p,
                Element e)
            {
                p = XYZ.Zero;
                var rc = false;
                var loc = e.Location;
                if (null != loc)
                {
                    if (loc is LocationPoint lp)
                    {
                        p = lp.Point;
                        rc = true;
                    }
                    else
                    {
                        var lc = loc as LocationCurve;
    
                        Debug.Assert(null != lc,
                            "expected location to be either point or curve");
    
                        p = lc.Curve.GetEndPoint(0);
                        rc = true;
                    }
                }
    
                return rc;
            }