本文整理汇总了C#中FilteredElementCollector.Cast方法的典型用法代码示例。如果您正苦于以下问题:C# FilteredElementCollector.Cast方法的具体用法?C# FilteredElementCollector.Cast怎么用?C# FilteredElementCollector.Cast使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FilteredElementCollector
的用法示例。
在下文中一共展示了FilteredElementCollector.Cast方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetAddressInStorage
/// <summary>
/// Get saved addresses in Storage. Currently only one address is supported
/// </summary>
/// <param name="document">The document storing the saved address.</param>
/// <param name="schema">The schema for address.</param>
/// <returns>List of stored addresses</returns>
private IList<DataStorage> GetAddressInStorage(Document document, Schema schema)
{
FilteredElementCollector collector = new FilteredElementCollector(document);
collector.OfClass(typeof(DataStorage));
Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid());
return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>();
}
示例2: LevelHasViews
/// <summary>
/// Checks if level has views.
/// </summary>
/// <param name="level">
/// The level.
/// </param>
/// <returns>
/// True if the level has views generated, false otherwise.
/// </returns>
public static bool LevelHasViews(Level level)
{
if (level == null)
return false;
FilteredElementCollector viewCollector = new FilteredElementCollector(level.Document);
viewCollector.OfClass(typeof(View));
Func<View, bool> viewIsNonTemplateAndGeneratedByLevel = view => !view.IsTemplate && IsViewGeneratedByLevel(view, level);
return viewCollector.Cast<View>().FirstOrDefault<View>(viewIsNonTemplateAndGeneratedByLevel) != null;
}
示例3: CreateLineStyle
/// <summary>
/// Create a new line style using NewSubcategory
/// </summary>
void CreateLineStyle(Document doc)
{
// Use this to access the current document in a macro.
//
//Document doc = this.ActiveUIDocument.Document;
// Find existing linestyle. Can also opt to
// create one with LinePatternElement.Create()
FilteredElementCollector fec
= new FilteredElementCollector( doc )
.OfClass( typeof( LinePatternElement ) );
LinePatternElement linePatternElem = fec
.Cast<LinePatternElement>()
.First<LinePatternElement>( linePattern
=> linePattern.Name == "Long dash" );
// The new linestyle will be a subcategory
// of the Lines category
Categories categories = doc.Settings.Categories;
Category lineCat = categories.get_Item(
BuiltInCategory.OST_Lines );
using( Transaction t = new Transaction( doc ) )
{
t.Start( "Create LineStyle" );
// Add the new linestyle
Category newLineStyleCat = categories
.NewSubcategory( lineCat, "New LineStyle" );
doc.Regenerate();
// Set the linestyle properties
// (weight, color, pattern).
newLineStyleCat.SetLineWeight( 8,
GraphicsStyleType.Projection );
newLineStyleCat.LineColor = new Color(
0xFF, 0x00, 0x00 );
newLineStyleCat.SetLinePatternId(
linePatternElem.Id,
GraphicsStyleType.Projection );
t.Commit();
}
}
示例4: GetOpeningsInWall
/// <summary>
/// Retrieve all openings in a given wall.
/// </summary>
void GetOpeningsInWall(
Document doc,
Wall wall)
{
ElementId id = wall.Id;
BuiltInCategory bic
= BuiltInCategory.OST_SWallRectOpening;
FilteredElementCollector collector
= new FilteredElementCollector( doc );
collector.OfClass( typeof( Opening ) );
collector.OfCategory( bic );
// explicit iteration and manual
// checking of a property:
List<Element> openings = new List<Element>();
foreach( Opening e in collector )
{
if( e.Host.Id.Equals( id ) )
{
openings.Add( e );
}
}
// using LINQ:
IEnumerable<Opening> openingsOnLevelLinq =
from e in collector.Cast<Opening>()
where e.Host.LevelId.Equals( id )
select e;
// using an anonymous method:
IEnumerable<Opening> openingsOnLevelAnon =
collector.Cast<Opening>().Where<Opening>( e
=> e.Host.Id.Equals( id ) );
}
示例5: GetSavedConfigurations
/// <summary>
/// Gets the saved setups from the document.
/// </summary>
/// <param name="document">The document storing the saved configuration.</param>
/// <returns>The saved configurations.</returns>
private IList<DataStorage> GetSavedConfigurations(Document document)
{
FilteredElementCollector collector = new FilteredElementCollector(document);
collector.OfClass(typeof(DataStorage));
Func<DataStorage, bool> hasTargetData = ds => ds.GetEntity(m_schema) != null;
return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>();
}
示例6: GetSavedConfigurations
/// <summary>
/// Gets the saved setups from the document.
/// </summary>
/// <returns>The saved configurations.</returns>
private IList<DataStorage> GetSavedConfigurations(Schema schema)
{
FilteredElementCollector collector = new FilteredElementCollector(IFCCommandOverrideApplication.TheDocument);
collector.OfClass(typeof(DataStorage));
Func<DataStorage, bool> hasTargetData = ds => (ds.GetEntity(schema) != null && ds.GetEntity(schema).IsValid());
return collector.Cast<DataStorage>().Where<DataStorage>(hasTargetData).ToList<DataStorage>();
}
示例7: findSketchPlane
/// <summary>
/// Return a sketch plane from the given document with
/// the specified normal vector, if one exists, else null.
/// </summary>
static SketchPlane findSketchPlane(
Document doc,
XYZ normal)
{
FilteredElementCollector collector
= new FilteredElementCollector( doc );
collector.OfClass( typeof( SketchPlane ) );
#if EXPLICIT_CODE
SketchPlane result = null;
foreach( SketchPlane e in collector )
{
if( e.Plane.Normal.IsAlmostEqualTo( normal ) )
{
result = e;
break;
}
}
return result;
#endif // EXPLICIT_CODE
//Func<SketchPlane, bool> normalEquals = e => e.Plane.Normal.IsAlmostEqualTo( normal ); // 2013
Func<SketchPlane, bool> normalEquals = e => e.GetPlane().Normal.IsAlmostEqualTo( normal ); // 2014
return collector.Cast<SketchPlane>().First<SketchPlane>( normalEquals );
}
示例8: IterateOverCollector
/// <summary>
/// Iterate directly over the filtered element collector.
/// In general, there is no need to create a copy of it.
/// Calling ToElements creates a copy, allocating space
/// for that and wasting both memory and time.
/// No need to cast either, foreach can do that
/// automatically.
/// </summary>
IEnumerable<Element> IterateOverCollector(
Document doc)
{
// Do not do this!
FilteredElementCollector collector
= new FilteredElementCollector( doc );
collector.OfClass( typeof( Family ) ).ToElements();
IEnumerable<Family> nestedFamilies
= collector.Cast<Family>();
String str = "";
foreach( Family f in nestedFamilies )
{
str = str + f.Name + "\n";
foreach( ElementId symbolId in
f.GetFamilySymbolIds() )
{
Element symbolElem = doc.GetElement(
symbolId );
str = str + " family type: "
+ symbolElem.Name + "\n";
}
}
// Iterate directly over the collector instead.
// No need for ToElements, which creates a copy.
// The copy wastes memory and time.
// No need for a cast, even.
FilteredElementCollector families
= new FilteredElementCollector( doc )
.OfClass( typeof( Family ) );
foreach( Family f in families )
{
str = str + f.Name + "\n";
// ...
}
return families;
}
示例9: WriteElementGeometry
private void WriteElementGeometry( int elementId )
{
FilteredElementCollector viewCollector = new FilteredElementCollector( m_doc );
viewCollector.OfClass( typeof( ViewPlan ) );
Func<ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan;
m_targetView = viewCollector.Cast<ViewPlan>().First<ViewPlan>( isLevel1FloorPlan );
Transaction createCurve = new Transaction( m_doc, "Create reference curves" );
createCurve.Start();
const double xReferenceLocation = 30;
Line vLine = Line.CreateBound( new XYZ( xReferenceLocation, 0, 0 ), new XYZ( xReferenceLocation, 20, 0 ) );
m_vLine = m_doc.Create.NewDetailCurve( m_targetView, vLine );
const double yReferenceLocation = -10;
Line hLine = Line.CreateBound( new XYZ( 0, yReferenceLocation, 0 ), new XYZ( 20, yReferenceLocation, 0 ) );
m_hLine = m_doc.Create.NewDetailCurve( m_targetView, hLine );
createCurve.Commit();
Element e = m_doc.GetElement( new ElementId( elementId ) );
Options options = new Options();
options.ComputeReferences = true;
options.IncludeNonVisibleObjects = true;
options.View = m_targetView;
GeometryElement geomElem = e.get_Geometry( options );
foreach( GeometryObject geomObj in geomElem )
{
if( geomObj is Solid )
{
WriteSolid( (Solid) geomObj );
}
else if( geomObj is GeometryInstance )
{
TraverseGeometryInstance( (GeometryInstance) geomObj );
}
else
{
m_writer.WriteLine( "Something else - " + geomObj.GetType().Name );
}
}
foreach( Curve curve in m_referencePlaneReferences )
{
// Try to get the geometry object from reference
Reference curveReference = curve.Reference;
GeometryObject geomObj = e.GetGeometryObjectFromReference( curveReference );
if( geomObj != null )
{
m_writer.WriteLine( "Curve reference leads to: " + geomObj.GetType().Name );
}
}
// Dimension to reference curves
foreach( Curve curve in m_referencePlaneReferences )
{
DetailCurve targetLine = m_vLine;
Line line = (Line) curve;
XYZ lineStartPoint = line.GetEndPoint( 0 );
XYZ lineEndPoint = line.GetEndPoint( 1 );
XYZ direction = lineEndPoint - lineStartPoint;
Line dimensionLine = null;
if( Math.Abs( direction.Y ) < 0.0001 )
{
targetLine = m_hLine;
XYZ dimensionLineStart = new XYZ( lineStartPoint.X + 5, lineStartPoint.Y, 0 );
XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X, dimensionLineStart.Y + 10, 0 );
dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd );
}
else
{
targetLine = m_vLine;
XYZ dimensionLineStart = new XYZ( lineStartPoint.X, lineStartPoint.Y + 5, 0 );
XYZ dimensionLineEnd = new XYZ( dimensionLineStart.X + 10, dimensionLineStart.Y, 0 );
dimensionLine = Line.CreateBound( dimensionLineStart, dimensionLineEnd );
}
ReferenceArray references = new ReferenceArray();
references.Append( curve.Reference );
references.Append( targetLine.GeometryCurve.Reference );
Transaction t = new Transaction( m_doc, "Create dimension" );
t.Start();
m_doc.Create.NewDimension( m_targetView, dimensionLine, references );
t.Commit();
}
}
示例10: Execute
//.........这里部分代码省略.........
+ "{1}, since Revit will refuse to handle such "
+ "a large mesh anyway. "
+ "Please refer to the troubleshooting page at "
+ "\r\n\r\n{2}\r\n\r\n"
+ "for suggestions on how to optimise the mesh "
+ "and thus reduce its size.",
vertices.Count, Config.MaxNumberOfVertices,
TroubleshootingUrl );
TaskDialog.Show( App.Caption, msg );
return Result.Failed;
}
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
string appGuid
= uiapp.ActiveAddInId.GetGUID().ToString();
string shapeName = Util.Capitalize(
Path.GetFileNameWithoutExtension( _filename )
.Replace( '_', ' ' ) );
// Retrieve "<Sketch>" graphics style,
// if it exists.
FilteredElementCollector collector
= new FilteredElementCollector( doc )
.OfClass( typeof( GraphicsStyle ) );
GraphicsStyle style
= collector.Cast<GraphicsStyle>()
.FirstOrDefault<GraphicsStyle>( gs
=> gs.Name.Equals( "<Sketch>" ) );
ElementId graphicsStyleId = null;
if( style != null )
{
graphicsStyleId = style.Id;
}
Result rc = Result.Failed;
try
{
using( Transaction tx = new Transaction( doc ) )
{
tx.Start( "Create DirectShape from OBJ" );
int nFaces = 0; // set to -1 on fatal error
int nFacesTotal = 0;
if( 0 < obj_load_result.Model.UngroupedFaces.Count )
{
nFacesTotal = nFaces = NewDirectShape( vertices,
obj_load_result.Model.UngroupedFaces, doc,
graphicsStyleId, appGuid, shapeName );
}
if( -1 < nFaces )
{
foreach( Group g in obj_load_result.Model.Groups )
{
示例11: InitCustomPropertySets
/// <summary>
/// Initializes custom property sets from schedules.
/// </summary>
/// <param name="propertySets">List to store property sets.</param>
/// <param name="fileVersion">The IFC file version.</param>
private static void InitCustomPropertySets(IList<IList<PropertySetDescription>> propertySets)
{
Document document = ExporterCacheManager.Document;
IList<PropertySetDescription> customPropertySets = new List<PropertySetDescription>();
// Collect all ViewSchedules from the document to use as custom property sets.
FilteredElementCollector viewScheduleElementCollector = new FilteredElementCollector(document);
ElementFilter viewScheduleElementFilter = new ElementClassFilter(typeof(ViewSchedule));
viewScheduleElementCollector.WherePasses(viewScheduleElementFilter);
List<ViewSchedule> filteredSchedules = viewScheduleElementCollector.Cast<ViewSchedule>().ToList();
int unnamedScheduleIndex = 1;
string includePattern = "PSET|IFC|COMMON";
if (ExporterCacheManager.ExportOptionsCache.PropertySetOptions.ExportSpecificSchedules)
{
var resultQuery =
from viewSchedule in viewScheduleElementCollector
where viewSchedule.Name != null &&
System.Text.RegularExpressions.Regex.IsMatch(viewSchedule.Name, includePattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
select viewSchedule;
filteredSchedules = resultQuery.Cast<ViewSchedule>().ToList();
}
foreach (ViewSchedule schedule in filteredSchedules)
{
//property set Manufacturer Information
PropertySetDescription customPSet = new PropertySetDescription();
string scheduleName = schedule.Name;
if (string.IsNullOrWhiteSpace(scheduleName))
{
scheduleName = "Unnamed Schedule " + unnamedScheduleIndex;
unnamedScheduleIndex++;
}
customPSet.Name = scheduleName;
ScheduleDefinition definition = schedule.Definition;
if (definition == null)
continue;
// The schedule will be responsible for determining which elements to actually export.
customPSet.ViewScheduleId = schedule.Id;
customPSet.EntityTypes.Add(IFCEntityType.IfcProduct);
int fieldCount = definition.GetFieldCount();
if (fieldCount == 0)
continue;
HashSet<ElementId> containedElementIds = new HashSet<ElementId>();
FilteredElementCollector elementsInViewScheduleCollector = new FilteredElementCollector(document, schedule.Id);
foreach (Element containedElement in elementsInViewScheduleCollector)
{
containedElementIds.Add(containedElement.Id);
}
ExporterCacheManager.ViewScheduleElementCache.Add(new KeyValuePair<ElementId, HashSet<ElementId>>(schedule.Id, containedElementIds));
IDictionary<ElementId, Element> cachedElementTypes = new Dictionary<ElementId, Element>();
for (int ii = 0; ii < fieldCount; ii++)
{
ScheduleField field = definition.GetField(ii);
ScheduleFieldType fieldType = field.FieldType;
if (fieldType != ScheduleFieldType.Instance && fieldType != ScheduleFieldType.ElementType)
continue;
ElementId parameterId = field.ParameterId;
if (parameterId == ElementId.InvalidElementId)
continue;
// We use asBuiltInParameterId to get the parameter by id below. We don't want to use it later, however, so
// we store builtInParameterId only if it is a proper member of the enumeration.
BuiltInParameter asBuiltInParameterId = (BuiltInParameter)parameterId.IntegerValue;
BuiltInParameter builtInParameterId =
Enum.IsDefined(typeof(BuiltInParameter), asBuiltInParameterId) ? asBuiltInParameterId : BuiltInParameter.INVALID;
Parameter containedElementParameter = null;
// We could cache the actual elements when we store the element ids. However, this would almost certainly take more
// time than getting one of the first few elements in the collector.
foreach (Element containedElement in elementsInViewScheduleCollector)
{
if (fieldType == ScheduleFieldType.Instance)
containedElementParameter = containedElement.get_Parameter(asBuiltInParameterId);
// shared parameters can return ScheduleFieldType.Instance, even if they are type parameters, so take a look.
if (containedElementParameter == null)
{
ElementId containedElementTypeId = containedElement.GetTypeId();
Element containedElementType = null;
if (containedElementTypeId != ElementId.InvalidElementId)
{
//.........这里部分代码省略.........
示例12: ExportToLux
// main function
public void ExportToLux()
{
//loop through views and export to lux
foreach (Autodesk.Revit.DB.View3D ExportView in v3DViewToExport)
{
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//set up list geoFile to include
List<String>GeoFileList = new List<string>();
//get all elements in view
FilteredElementCollector viewCollector = new FilteredElementCollector(vDoc, ExportView.Id);
//i could add a filter for each category here ( or for specials like lights...)
//viewCollector.OfCategory(BuiltInCategory.OST_Walls);
//cast views elements to list
IEnumerable<Element> ElementList = viewCollector.Cast<Element>();
//create scene folder
//check whether folder allready exists
//if not create scene folder
//create PLY folder
//create RES folder (textures & other data)
if (Directory.Exists(vOutputFilePath + ExportView.Name.ToString()))
{
//delete folder??
}
else
{
//create all directories
//make sure view name has no illegal characters: {}
//create scene Directory
Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString());
//create PLY folder
Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString() + "/" + "PLY");
//create resources folder
Directory.CreateDirectory(vOutputFilePath + ExportView.Name.ToString() + "/" + "RES");
}
//set up geofile path variable
String sOutputPathGeoFile = "";
//setup PLY path variable
String PLYDirectory = "";
//check for linked Revit Files visible in view
LuxExporter.Revit_Filter Filter = new Revit_Filter(vDoc);
List<Element> RevitLinks = Filter.GetRevitLinks(ExportView.Id);
//setup the geomtry option for the current view
Autodesk.Revit.DB.Options GeometryOption = new Options();
GeometryOption.ComputeReferences = true;
GeometryOption.View = ExportView;
//export linked files
if (RevitLinks.Count > 0)
{
//count how many instances of each individual link exist
//check whether any of these instances collides with section box if there is any
//if collision no instance, if no collision or no section box instanciate whole file
//export link file and instanciate as often as required
//create dictionary storing linked file name and number of occurences
Dictionary<String, int> DRevitLinks = new Dictionary<string, int>();
//list containing all links of models not cut by section box and their transformation data
List<LuxExporter.Revit_Linked_Files> lWholeModelLinks = new List<Revit_Linked_Files>();
//list containing all links of models cut by section box and their transformation data
List<LuxExporter.Revit_Linked_Files> lCutModelLinks = new List<Revit_Linked_Files>();
int LinkCounter = 0;
//loop through link list and sort items before exporting
foreach (Element LinkItem in RevitLinks)
{
//increase link Counter
LinkCounter++;
//remove stuff from name
String LinkName = LinkItem.Name.ToString().Substring(0, LinkItem.Name.ToString().IndexOf(".rvt"));
//flag for bounding box check
Boolean BoundingBoxOK = true;
//check whether bounding box active
//pointer
int NumberOfLinkOccurences = 0;
if (ExportView.SectionBox.Enabled)
{
//if yes does link clash with box?
//get boundingbox of item
BoundingBoxXYZ ElementBounding = LinkItem.get_BoundingBox(ExportView);
//get sectionbox
Autodesk.Revit.DB.BoundingBoxXYZ ViewSectionBox = ExportView.SectionBox;
//check whether element bounding box is completely enclosed in view bounding box if not disable instancing!
LuxExporter.Revit_BoundingBox_Checker checker = new Revit_BoundingBox_Checker();
BoundingBoxOK = checker.BoundingBox_Checker(ElementBounding, ViewSectionBox);
}
//.........这里部分代码省略.........