Conditionally add an item in list initialization

Viewed 1724

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.

2 Answers

If this pattern occurs a lot in your code, you could consider creating a couple of extension methods that can be used to build a method chain for appending items to a List<T>.

Something like this:

public static class ListExtensions
{
    public static List<T> Append<T>(this List<T> list, params T[] values)
    {
        list.AddRange(values);
        return list;
    }

    public static List<T> AppendIf<T>(this List<T> list, bool condition, params T[] values)
    {
        return condition ? list.Append(values) : list;
    }
}

And then build the list in this way:

myListByOrder
    .Append(item1, item2)
    .AppendIf(condition, item3)
    .Append(item4, item5);

No, array initialisers must be of a fixed length known at compile time.

But there are plenty of alternatives as I'm sure you know. If you're adding items to a list anyway, you might as well add them in separate statements.

Related