Finding a Shape in a PowerPoint Presentation by Name

As part of how we construct templates, all objects we want to manipulate are named using the Selection Pane.

While the Find by Alt Text example was handy, it doesn’t really suit the way we work, so wrote my own solution (that has to take nested groupshapes into consideration) and allows me to quickly find an index for a shape given the name.

In case it’s useful, thought I’d share (feel free to remove/reuse)

to call:

ISlide slide = presentation.Slides[i];
List<IShape> shapes = Utilities.GetShapes(slide);

to find a shape index:

int shape_ix = shapes.FindIndex(o => o.Name == "{name-to-find}");

and then you can reference the object as shapes(shape_ix).

The code itself:

public static List<IShape> GetShapes(ISlide slide, bool sort = true)
{
    List<IShape> shapes = new List<IShape>();
    foreach (IShape sh in slide.Shapes)
    {
        shapes.Add(sh);
        if (sh is GroupShape)
        {
            GetChildShapes((IGroupShape)sh, ref shapes);
        }
    }
    if (sort)
    {
        shapes.Sort((x, y) => x.Name.CompareTo(y.Name));
    }
    return shapes;
}


public static void GetChildShapes(IGroupShape groupShapes, ref List<IShape> shapes)
{
    foreach (IShape sh in groupShapes.Shapes)
    {
        shapes.Add(sh);
        if (sh is GroupShape)
        {
            GetChildShapes((IGroupShape)sh, ref shapes);
        }
    }
}

@jcath,
I think this approach will be useful to someone. Thank you for the code examples and for using Aspose.Slides.