Collections and Iterators

Collections and Iterators

In the Revit Platform API, Collections and Iterators are generic and type safe.

All collections implement the IEnumerable interface and all relevant iterators implement the IEnumerator interface. As a result, all methods and properties are implemented in the Revit Platform API and can play a role in the relevant collections.

Implementing all of the collections is similar. The following example uses ModelCurveArray to demonstrate how to use the main collection properties:

Code Region 9-2: Using collections

UIDocument uidoc = new UIDocument(document); 
ICollection<ElementId> selectedIds = uidoc.Selection.GetElementIds();
            
// Store the ModelLine references
ModelCurveArray lineArray = new ModelCurveArray();
            
// … Store operation
Autodesk.Revit.DB.ElementId id = new Autodesk.Revit.DB.ElementId(131943); //assume 131943 is a model line element id
lineArray.Append(document.GetElement(id) as ModelLine);

// use Size property of Array
TaskDialog.Show("Revit","Before Insert: " + lineArray.Size + " in lineArray.");

// use IsEmpty property of Array
if (!lineArray.IsEmpty)
{
    // use Item(int) property of Array
    ModelCurve modelCurve = lineArray.get_Item(0) as ModelCurve;

    // erase the specific element from the set of elements
    selectedIds.Remove(modelCurve.Id);

    // create a new model line and insert to array of model line
    SketchPlane sketchPlane = modelCurve.SketchPlane;

    XYZ startPoint = new XYZ(0, 0, 0);  // the start point of the line
    XYZ endPoint = new XYZ(10, 10, 0);  // the end point of the line
    // create geometry line
    Line geometryLine = Line.CreateBound(startPoint, endPoint);

    // create the ModelLine
    ModelLine line = document.Create.NewModelCurve(geometryLine, sketchPlane) as ModelLine;

    lineArray.Insert(line, lineArray.Size - 1);
}

TaskDialog.Show("Revit","After Insert: " + lineArray.Size + " in lineArray.");

// use the Clear() method to remove all elements in lineArray
lineArray.Clear();

TaskDialog.Show("Revit","After Clear: " + lineArray.Size + " in lineArray.");