Split ModelItemCollection of Navisworks .NET API

By Xiaodong Liang

Issue
Is there an efficient way to split or partition a existing ModelItemCollection to serveral ModelItemCollections?

Solution
This is a generic question of IEnumerable. The code below splits the ModelItemCollection to 3 sections with LINQ. The demo references the material in

http://stackoverflow.com/questions/438188/split-a-collection-into-n-parts-with-linq

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Linq;
using Autodesk.Navisworks.Api;
using Autodesk.Navisworks.Api.Plugins;
// help class to do split
static class LinqExtensions
{
    public static IEnumerable
        Split(this IEnumerable list, int parts)
    {
        int i = 0;
        var splits = from name in list
                        group name by i++ % parts into part
                        select part.AsEnumerable();
        return splits;
    }
}
void test()
{
    Document oDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;
 
    // assume we get some items from the selected objects.
    ModelItemCollection oModelItems = 
        oDoc.CurrentSelection.SelectedItems;
 
    IEnumerable finalCollectionArray =
        (IEnumerable)
         LinqExtensions.Split(oModelItems, 3);
}

Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading