Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inline conditional in string[] array

How could you do the following inline conditional for a string[] array in C#. Based on a parameter, I'd like to include a set of strings...or not. This question is a followup of this one on stackoverflow.

        //Does not compile
        bool msettingvalue=false;
        string[] settings;
        if(msettingvalue)
            settings = new string[]{
                "setting1","1",
                "setting2","apple",
                ((msettingvalue==true) ? "msetting","true" :)};

If msettingvalue is true, I'd like to include two strings "msetting","true" : otherwise no strings.

Edit1 It doesn't have to be a key value pair...what if it were 5 strings to be (or not to be) added...I didn't think it'd be that tricky.

(Also...could someone with enough rep make a "inline-conditional" or "conditional-inline" tag?)

like image 341
Eugene Avatar asked Oct 17 '11 00:10

Eugene


1 Answers

settings = new string[]{"setting1","1", "setting2","apple"}
    .Concat(msettingvalue ? new string[] {"msetting","true"} : new string[0]);
    .ToArray()
like image 108
Ilia G Avatar answered Sep 19 '22 07:09

Ilia G