Find all categories with instances

Find all categories with instances

Anonymous
Not applicable
1,033 Views
4 Replies
Message 1 of 5

Find all categories with instances

Anonymous
Not applicable

Hello, everyone! I'm creating the add-in, some kind of custom filter, and firstly it fills ComboBox with all Categories in the project (code is attached below). 

But, in fact, some categories are empty and haven't any instances in the project, and they're useless in Combobox. 

 

 


public void CreateCategoryList() { FilteredElementCollector elements = new FilteredElementCollector (doc)
.WhereElementIsElementType();
categories = elements .Where(x => x.Category != null) .Select(x => x.Category) .Distinct(new CategoryComparer()) .ToList(); categories.Sort(new CategoryNameComparer()); foreach (Category c in categories) { ComboBoxItem cbi = new ComboBoxItem(); cbi.HorizontalContentAlignment = HorizontalAlignment.Left; cbi.Padding = new Thickness(30, 0, 0, 0); cbi.Content = c.Name; cbi.Tag = c; comboBox.Items.Add(cbi); } } 

 Can anyone help me to find only those categories which have instances in the project? Thanks!

0 Likes
1,034 Views
4 Replies
Replies (4)
Message 2 of 5

Anonymous
Not applicable

Hello, I do it this way:

 

 

var allElelements = new FilteredElementCollector(doc).WhereElementIsNotElementType()
                    .Where(x => (x.Category != null) && x.GetTypeId().IntegerValue != -1).ToList();
            var catsInModel = allElelements.Select(x => x.Category.Name).Distinct().ToList();

 

0 Likes
Message 3 of 5

Anonymous
Not applicable

Thanks, it works better than mine, but still not perfectly. There are 7-8 empty categories in the project. Thank you anyway!

0 Likes
Message 4 of 5

Anonymous
Not applicable

Can you give document? I would like to see these empty categories.

0 Likes
Message 5 of 5

Anonymous
Not applicable

There might be a more efficient way to do it but this seems to work for me:

 

List<string> categoriesList = new List<string>();

foreach (Category c in doc.Settings.Categories)
{
    bool foundInstance = false;

    foreach (Element elm in new FilteredElementCollector(doc)
        .WhereElementIsNotElementType()
        .OfCategoryId(c.Id))
    {
        foundInstance = true;
        break;
    }                

    if (foundInstance) categoriesList.Add(c.Name);
}

System.Windows.Forms.MessageBox.Show(
    string.Join(System.Environment.NewLine, categoriesList));

 

0 Likes