This post has an example of getting the top edge of surfaces by sorting Z values of their midpoints.