如何在 Revit 中检索嵌套族实例 API

How to retrieve nested family instances in Revit API

我正在使用 FilteredElementCollector 检索系列实例:

    var collector = new FilteredElementCollector(doc, doc.ActiveView.Id);
    var familyInstances = collector.OfClass(typeof(FamilyInstance));

这适用于没有嵌套家庭实例的家庭。但是如果我在项目中有A族的实例,A族本身包含B族的实例,这段代码就无法获取B族的实例。如何获取B族的实例?

我是 Revit 的新手 API,看来一定有一个简单的解决方案,但我在网上找不到。如果有影响的话,我正在使用 Revit 2015。

familyInstances 将包含活动视图中所有族的列表(包括嵌套和非嵌套)。

您需要做的是遍历每个 FamilyInstance 并查看它是否已经是根族(即包含嵌套族)或嵌套族或 none。类似于:

            var collector = new FilteredElementCollector(doc, doc.ActiveView.Id);
            var familyInstances = collector.OfClass(typeof(FamilyInstance));
            foreach (var anElem in familyInstances)
            {
                if (anElem is FamilyInstance)
                {
                    FamilyInstance aFamilyInst = anElem as FamilyInstance;
                    // we need to skip nested family instances 
                    // since we already get them as per below
                    if (aFamilyInst.SuperComponent == null)
                    {
                        // this is a family that is a root family
                        // ie might have nested families 
                        // but is not a nested one
                        var subElements = aFamilyInst.GetSubComponentIds();
                        if (subElements.Count == 0)
                        {
                            // no nested families
                            System.Diagnostics.Debug.WriteLine(aFamilyInst.Name + " has no nested families");
                        }
                        else
                        {
                            // has nested families
                            foreach (var aSubElemId in subElements)
                            {
                                var aSubElem = doc.GetElement(aSubElemId);
                                if (aSubElem is FamilyInstance)
                                {
                                    System.Diagnostics.Debug.WriteLine(aSubElem.Name + " is a nested family of " + aFamilyInst.Name);
                                }
                            }
                        }
                    }
                }
            }

我通常会大量使用 Linq 以留下更简洁的代码。看这个例子:

List<Element> listFamilyInstances = new FilteredElementCollector(doc, doc.ActiveView.Id)
            .OfClass(typeof(FamilyInstance))
            .Cast<FamilyInstance>()
            .Where(a => a.SuperComponent == null)
            .SelectMany(a => a.GetSubComponentIds())
            .Select(a => doc.GetElement(a))
            .ToList();