Using IEnumerable and LINQ with the Maya .NET API


Many classes in the Maya .NET API implement the IEnumerable<T> interface. Some examples include helper classes like MCGeometry, MCDag, and MCDependencyGraph, as well as the various Maya array classes such MColorArray, MFloatPointArray, and so forth. To see all classes that implement IEnumerable<T> you can use the Object Browser to search for GetEnumerator().

Any class that implements a GetEnumerator() function (including functions that implement IEnumerable) and returns a class that conforms to the IEnumerator interface can be used with the foreach keyword. For example, the following code snippet displays the path names of all selected objects.

foreach (var s in new MSelectionList())

If the System.Linq namespace is imported, then the LINQ extension methods can be used with all collections that implement IEnumerable<T>. For example, the following code snippet returns all selected meshes.

var meshes = new MSelectionList().Where(p => p.hasFn(MFn.Type.kMesh)).Select(p => new MFnMesh(p));

This is called the “method syntax”. The other syntax supported by LINQ is called “query syntax”. The following snippet is equivalent to the previous:

var meshes = from p in new MSelectionList() where p.hasFn(MFn.Type.kMesh) select new MFnMesh(p);

For more examples using LINQ, see the DAGExplorer example under the <...>\devkit\dotnet\wpfexamples folder.