Finding 3d views with one lovely long laborious LINQ and Lamda line

Language-Integrated Query (LINQ) and Lamda expressions are great ways to do a whole lot without writing much code.

Here is some code that improves on the previous post by excluding the view templates.

public void ThreeDViewsWithLinq()
{
    Document doc = this.ActiveUIDocument.Document;
    IList<View3D> viewList = new FilteredElementCollector(doc).OfClass(typeof(View3D)).Cast<View3D>().Where(v => v.IsTemplate == false).ToList();
    string views = "";
    foreach (View3D view in viewList)
    {
        views += view.Name + "-" + view.IsPerspective + "\n";
    }
    TaskDialog.Show("3D Views", views);
}

Here are the pieces that go together to define the objects found by the FilteredElementCollector.

  • OfClass(typeof(View3D)) has been shown in previous examples as a way to restrict the filter to 3d views
  • Cast<View3D>() converts the items from generic Element objects to View3D objects. Later on, when we want to check the IsPerspective property, the objects will need to be View3D objects (because IsPerspective is a property of View3D, not a property of Element). Also, to do the lamda expression that evaluates a view property (IsTemplate) we need to cast to the View class (or a sub-class such as View3D).
  • Where(v => v.IsTemplate == false) is the lamda expression. Microsoft defines a lambda expression as ” an anonymous function that you can use to create delegates or expression tree types”. Whatever. I’d rather say it is a way to include only objects that pass some logical statement. In this case, the IsTemplate property of the views must be false.
  • ToList() converts this bunch of view3D objects into a list

You don’t need to understand all the computer science stuff behind LINQ and lambda expressions to use them. The line of code above can be copied and reused as you need, changing View3D to some other class and “IsTemplate == false” to some other statement.

3dlinq

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s