public ElementCollection GroupByCategory() { // Fill a dictionary by elements categories Dictionary <string, ElementCollection> categoryDict = new Dictionary <string, ElementCollection>(); foreach (ElementContainer elemCont in Rvt.Data.PickedElements) { if (categoryDict.Keys.Contains(elemCont.CategoryName) == false) { categoryDict.Add(elemCont.CategoryName, new ElementCollection()); } categoryDict[elemCont.CategoryName].Add(elemCont); } // Create a new element collection filled by the dictionary order ElementCollection groupedCol = new ElementCollection(); foreach (var pair in categoryDict) { groupedCol.Add(new ElementContainer(pair.Key)); // Add category line groupedCol.AddElementCollection(pair.Value); // Add elements of category } return(groupedCol); }