FAQ: [23.2] How to JOIN multiple lines to polylines?
Simply try to join each element with all selected, but beware thata entity already joined cannot be entget'ed anymore, because it's deleted.
;;; This sample converts all selected elements to polylines and
;;; tries to join as much as possible.
(defun C:JOINPOLY (/ ele ss) (foreach ele (std-sslist (setq ss (ssget)))
(if (entget ele)
;not already joined
(cond ((std-entity-type-p ele '("ARC" "LINE"))
;; in fact you should check Z of lines and UCS here too
(command "_PEDIT" ele "_Y" "_J" ss "" "")
; convert+JOIN
) ((and (std-entity-type-p ele '("POLYLINE" "LWPOLYLINE"))
(not (std-flagsetp 1 ele))
;not closed
(< (rem (std-getflag ele) 128) 8))
;ignore meshes
(command "_PEDIT" ele "_J" ss "" "")
;ucs check omitted
) ) ) ) )