I want to add some range of items to my list initialization but sometimes I don't want to add an item based on a condition , I tried below with ternary operator , but it adds null to my list. Is there a way I can completely skip adding a particular item if condition is met ? I can do this without using initialization in a separate if block but I am looking for a solution which can be done in same initialization statement. To be more clear with my problem ,my list should have different order of items based on a flag
var myListByOrder= new List<Object>();
if(flag)
{
MyListByOrder.AddRange( new []
{
item1,
item2,
condition ? item3: null,
item 4,
item 5
});
}
else
{
MyListByOrder.AddRange( new []
{
item5,
item3,
condition? item7 :null
item 1,
item 2
});
}
Now just because of a condition I dont want to break the readability of code and provide extra if-else, Is there a solution to it , which can keep this same and skip the elements if condition is met. Another way is, I can remove the nulls from array after filling them in above way.