Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# how to use ternary conditional inside LINQ Select

Basically, I am working with Revit API (Civil Engineering 3D modeling program) combined with C#.

In this case I need to populate a WPF List Box with names of the elements. To do so, I use LINQ as such:

beamTypes = new FilteredElementCollector(doc)
                .OfCategory(BuiltInCategory.OST_StructuralFraming)
                .OfClass(typeof(FamilyInstance))

                .Select(x => x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK) as Parameter).AsString())
              
                .Distinct();

It would work like a charm if every element had a MARK, which is the custom name my costumer enginner uses. However, not every element has a defined MARK and when it doesn’t I would like to select the Element.Name.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Would be something like this:

.Select(x => (x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK) as Parameter).AsString().Equals("") ? x.Name : (x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK) as Parameter).AsString())

How can I correctly use the ternary inside my LINQ .Select?

>Solution :

It sounds like this should work for you

.Select(x => {
    if (x.get_Parameter(BuiltInParameter.ALL_MODEL_MARK) is Parameter _param)
        return _param.AsString();
    return x.Name;
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading