How do I query OCG layer groups?

Question:
I would like to display OCG layers by their order like how I see it in Adobe Reader. How can I query the layers by their grouping?

Answer:
You can do so by getting the OCGs by their order. The following sample C# code shows how you can do this:

static void HandleGroup(Obj group)
        {
            if (group.IsArray()) // it is an array of dicts or an array of arrays...
            {
                var wl = group.GetAt(0);
                Group ocg = new Group(wl);

                if (ocg.IsValid()) // if the array itself is an array of OCGs
                {
                    int sz = group.Size();
                    for (int x = 0; x < sz; x++)
                    {
                        HandleGroup(group.GetAt(x)); // handle the sublayers
                    }
                } else
                {
                    // handle array
                    Console.WriteLine(wl.GetAsPDFText());// 0 is the Name of the group
                    int sz = group.Size();
                    for (int x = 1; x < sz; x++)
                    {
                        HandleGroup(group.GetAt(x)); // handle the sublayers
                    }
                }  
            }
            else if (group.IsDict()) // it is a normal ocg, handle it
            {
                Group ocg = new Group(group);
                Console.WriteLine(ocg.GetName());
            }
        }

using (PDFDoc doc = new PDFDoc(@"ocg.pdf"))
            {
                // Now render each layer in the input document to a separate image.
                Obj ocgs = doc.GetOCGs(); // Get the array of all OCGs in the document.

                if (ocgs != null)
                {
                    var config = doc.GetOCGConfig();
                    var order = config.GetOrder();
                    if (order != null)
                    {
                        int i, sz = order.Size();
                        for (i = 0; i < sz; i++)
                        {
                            HandleGroup(order.GetAt(i)); // call the handle group helper function
                        }
                    }
                }
            }

`