I have a piece of code like below:
var selected = “A”;
bool isSelected = selected == "A" || selected == "C";
var codeLists = new
{
displayProperty1 = isSelected ? "property1" : null,
displayProperty2 = isSelected ? "property2" : null,
displayProperty3 = selected == "C" ? "property3" : null
};
So, my goal is to eliminate a property if it does not satisfy a condition. In the above code, selected is "A". So, displayProperty3 would have a value of null. But I want to eliminate displayProperty3 so that if selected is “A”, then there should be only 2 properties in the object.
If there is any proper and efficient way to do this, I would be grateful for it.
No, an anonymous type still follows the rules of other types, they’re just not explicitly defined at compile-time. To do what you want you’d have to define two different types.
If you don’t want to show that property in your UI (e.g. if you ware binding to a grid that’s auto-generated and you don’t want that to be a column) then deal with that in your UI.
However, if you HAVE to do this, you’d have to create two different types (either anonymous or explicit):
It would be better if you created a base type with the common properties, but either way they are going to be two different types: