Home > Enterprise >  C# how to use ternary conditional inside LINQ Select
C# how to use ternary conditional inside LINQ Select

Time:01-27

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.

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?

CodePudding user response:

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;
})
  •  Tags:  
  • Related